iOS
...
Data Objects
Управление связями данных в ParseSwift SDK для разработчиков iOS
16 мин
отношения введение отношения являются основным элементом для организации объектов данных, хранящихся в базе данных parseswift предоставляет необходимые инструменты и методы для установления отношений между классами в вашей базе данных back4app в зависимости от случая использования, мы можем выделить следующие типы отношений 1 1 отношение, которое соединяет только два объекта данных 1\ n отношение между одним объектом данных и n n объектами данных n\ n отношение между n n объектами данных и n n объектами данных как мы увидим ниже, реализация 1 1 отношений относительно проста для 1\ n и n\ n отношений реализация включает в себя объект parserelation parserelation предоставленный parseswift sdk существуют дополнительные альтернативы для реализации 1\ n и n\ n отношений однако, из за эффективности и производительности, мы рекомендуем следовать нашему подходу этот учебник использует базовое приложение, созданное в xcode 12 и ios 14 в любое время вы можете получить доступ к полному проекту через наши репозитории на github https //github com/templates back4app/ios crud to do list цель чтобы понять, как отношения реализованы в базе данных back4app предварительные требования чтобы завершить этот быстрый старт, вам нужно xcode приложение, созданное в back4app следуйте за https //www back4app com/docs/get started/new parse app чтобы узнать, как создать приложение parse в back4app примечание следуйте за https //www back4app com/docs/ios/parse swift sdk чтобы создать проект xcode, подключенный к back4app понимание нашего приложения для книг шаблон проекта это приложение для книг, где пользователь вводит данные о книге, чтобы сохранить их в базе данных back4app на главном экране приложения вы найдете форму для этого используя кнопку + + расположенную в верхнем правом углу навигационной панели, мы можем добавить столько издателей , жанров и авторов сколько необходимо как только пользователь вводит книгу, он может использовать кнопку добавить книгу добавить книгу чтобы сохранить книгу в своей базе данных back4app кроме того, кнопка список книг список книг позволит нам показать все книги, которые добавил пользователь, а также увидеть их связь с издателями и авторами быстрая справка по командам, которые мы собираемся использовать мы используем объекты автор автор , издатель издатель , isbn isbn и книга книга genre 1 import foundation 2 import parseswift 3 4 struct genre parseobject { 5 6 7 var name string? 8 9 10 } author 1 import foundation 2 import parseswift 3 4 struct author parseobject { 5 6 7 var name string? 8 9 10 } publisher 1 import foundation 2 import parseswift 3 4 struct publisher parseobject { 5 6 7 var name string? 8 9 10 } isbn 1 import foundation 2 import parseswift 3 4 struct isbn parseobject { 5 6 7 var name string? 8 9 10 } book 1 import foundation 2 import parseswift 3 4 struct book parseobject { 5 6 7 var title string? 8 var publishingyear int? 9 var genre genre? 10 var isbn isbn? 11 12 13 } перед сохранением экземпляров этих объектов в базе данных back4app все их свойства должны соответствовать протоколам codable codable и hashable hashable мы используем следующие методы для управления этими объектами в базе данных back4app create //when creating a new instance of author we use 1 var newauthor author = author(name "john doe") 2 3 // saves newauthor on your back4app database synchronously and returns the new saved item it throws and error if something went wrong 4 let savedauthor = try? newauthor save() 5 6 // saves newauthor on your back4app database asynchronously, and passes a result\<author, parseerror> object to the completion block to handle the save process 7 newauthor save { result in 8 // handle the result to check wether the save process was successfull or not 9 } read //for reading any of the objects introduced above, we construct the corresponding queries for each of them for author we have 1 let authorquery = author query() // a query to fetch all author items on your back4app database 2 3 // fetches the items synchronously or throws an error if found 4 let fetchedauthors = try? query find() 5 6 // fetches the items asynchronously and calls a completion block passing a result object containing the result of the operation 7 query find { result in 8 // handle the result 9 } add relations //in 1 1 relations, it is sufficient to have the child object as a property of the parent object back4app automatically saves the child object when the parent object is saved for the remaining relations, we use the add( objects ) method via the relation property available in the parent parseobject adding a relation called authors on a book object would look like this 1 let somebook book 2 let authors \[author] 3 4 // adds the relation between somebook and authors under the name 'authors' 5 let booktoauthorsrelation = try? somebook relation? add("authors", objects authors) 6 7 // saves the relation synchronously 8 let updatedsomebook = try? booktoauthorsrelation save() 9 10 // saves the relation asynchronously 11 booktoauthorsrelation save { result in 12 // handle the result 13 } query relations //for 1 1 relations, it is enough to append the include() method in the query for instance, to query all the books together with their isbn relation, we use 1 var query = book query() include("isbn") 2 3 // fetches all books synchronously 4 let books = try? query find() 5 6 // fetches all books asynchronously 7 query find { result in 8 // handle the result 9 } remaining relations //for the remaining relations, we create a query by using the static method queryrelation( ,parent ) provided by the parseobject protocol querying the authors related to a book can be implemented in the following way 1 let somebook book 2 let authors \[author] 3 4 5 // we create a relation (identified by the name 'authors') betwee somebook and a set of authors 6 let booktoauthorsrelation = 7 guard let booktoauthorsrelation = try somebook relation? add("authors", objects authors) // book > author 8 else { 9 fatalerror("failed to add relation") 10 } 11 12 let savedrelation = try booktoauthorsrelation save() // saves the relation synchronously 13 14 booktoauthorsrelation save { result in // saves the relation asynchronously 15 // handle the result 16 } 1 скачайте шаблон приложения для книг проект xcode xcode имеет следующую структуру в любое время вы можете получить доступ к полному проекту через наши репозитории на github https //github com/templates back4app/ios crud to do list 2 дополнительный поток crud перед тем как продолжить, необходимо реализовать некоторые функции crud, чтобы мы могли сохранить автора автора , издателя издателя и жанра жанра объектов в файле maincontroller+parseswift swift maincontroller+parseswift swift под расширением для класса maincontroller maincontroller мы реализовали следующие методы 1 // maincontroller+parseswift swift file 2 extension maincontroller { 3 /// collects the data to save an instance of book on your back4app database 4 func savebook() { 5 view\ endediting(true) 6 7 // 1 first retrieve all the information for the book (title, isbn, etc) 8 guard let booktitle = booktitletextfield text else { 9 return presentalert(title "error", message "invalid book title") 10 } 11 12 guard let isbnvalue = isbntextfield text else { 13 return presentalert(title "error", message "invalid isbn value ") 14 } 15 16 let query = isbn query("value" == isbnvalue) 17 18 guard (try? query first()) == nil else { 19 return presentalert(title "error", message "the entered isbn already exists ") 20 } 21 22 guard let genreobjectid = genreoptionsview\ selectedoptionids first, 23 let genre = genres first(where { $0 objectid == genreobjectid}) 24 else { 25 return presentalert(title "error", message "invalid genre ") 26 } 27 28 guard let publishingyearstring = publishingyeartextfield text, let publishingyear = int(publishingyearstring) else { 29 return presentalert(title "error", message "invalid publishing year ") 30 } 31 32 let authors \[author] = self authoroptionsview\ selectedoptionids compactmap { \[weak self] objectid in 33 self? authors first(where { objectid == $0 objectid }) 34 } 35 36 let publishers \[publisher] = self publisheroptionsview\ selectedoptionids compactmap { \[weak self] objectid in 37 self? publishers first(where { objectid == $0 objectid }) 38 } 39 40 // since we are making multiple requests to back4app, it is better to use synchronous methods and dispatch them on the background queue 41 dispatchqueue global(qos background) async { 42 do { 43 let isbn = isbn(value isbnvalue) // 2 instantiate a new isbn object 44 45 let savedbook = try book( // 3 instantiate a new book object with the corresponding input fields 46 title booktitle, 47 publishingyear publishingyear, 48 genre genre, 49 isbn isbn 50 ) save() // 4 save the new book object 51 52 // here we will implement the relations 53 54 dispatchqueue main async { 55 self presentalert(title "success", message "book saved successfully ") 56 } 57 } catch { 58 dispatchqueue main async { 59 self presentalert(title "error", message "failed to save book \\((error as! parseerror) message)") 60 } 61 } 62 } 63 } 64 65 /// retrieves all the data saved under the genre class in your back4app database 66 func fetchgenres() { 67 let query = genre query() 68 69 query find { \[weak self] result in 70 switch result { 71 case success(let genres) 72 self? genres = genres // when setting self? genres, it triggers the corresponding ui update 73 case failure(let error) 74 self? presentalert(title "error", message error message) 75 } 76 } 77 } 78 79 /// presents a simple alert where the user can enter the name of a genre to save it on your back4app database 80 func handleaddgenre() { 81 // displays a form with a single input and executes the completion block when the user presses the submit button 82 presentform( 83 title "add genre", 84 description "enter a description for the genre", 85 placeholder nil 86 ) { \[weak self] name in 87 guard let name = name else { return } 88 let genre = genre(name name) 89 90 let query = genre query("name" == name) 91 92 guard ((try? query first()) == nil) else { 93 self? presentalert(title "error", message "this genre already exists ") 94 return 95 } 96 97 genre save { \[weak self] result in 98 switch result { 99 case success(let addedgenre) 100 self? presentalert(title "success", message "genre added!") 101 self? genres append(addedgenre) 102 case failure(let error) 103 self? presentalert(title "error", message "failed to save genre \\(error message)") 104 } 105 } 106 } 107 } 108 109 /// retrieves all the data saved under the publisher class in your back4app database 110 func fetchpublishers() { 111 let query = publisher query() 112 113 query find { \[weak self] result in 114 switch result { 115 case success(let publishers) 116 self? publishers = publishers 117 case failure(let error) 118 self? presentalert(title "error", message error message) 119 } 120 } 121 } 122 123 /// presents a simple alert where the user can enter the name of a publisher to save it on your back4app database 124 func handleaddpublisher() { 125 // displays a form with a single input and executes the completion block when the user presses the submit button 126 presentform( 127 title "add publisher", 128 description "enter the name of the publisher", 129 placeholder nil 130 ) { \[weak self] name in 131 guard let name = name else { return } 132 133 let query = publisher query("name" == name) 134 135 guard ((try? query first()) == nil) else { 136 self? presentalert(title "error", message "this publisher already exists ") 137 return 138 } 139 140 let publisher = publisher(name name) 141 142 publisher save { \[weak self] result in 143 switch result { 144 case success(let addedpublisher) 145 self? presentalert(title "success", message "publisher added!") 146 self? publishers append(addedpublisher) 147 case failure(let error) 148 self? presentalert(title "error", message "failed to save publisher \\(error message)") 149 } 150 } 151 } 152 } 153 154 /// retrieves all the data saved under the genre class in your back4app database 155 func fetchauthors() { 156 let query = author query() 157 158 query find { \[weak self] result in 159 switch result { 160 case success(let authors) 161 self? authors = authors 162 case failure(let error) 163 self? presentalert(title "error", message error message) 164 } 165 } 166 } 167 168 /// presents a simple alert where the user can enter the name of an author to save it on your back4app database 169 func handleaddauthor() { 170 // displays a form with a single input and executes the completion block when the user presses the submit button 171 presentform( 172 title "add author", 173 description "enter the name of the author", 174 placeholder nil 175 ) { \[weak self] name in 176 guard let name = name else { return } 177 178 let query = author query("name" == name) 179 180 guard ((try? query first()) == nil) else { 181 self? presentalert(title "error", message "this author already exists ") 182 return 183 } 184 185 let author = author(name name) 186 187 author save { \[weak self] result in 188 switch result { 189 case success(let addedauthor) 190 self? presentalert(title "success", message "author added!") 191 self? authors append(addedauthor) 192 case failure(let error) 193 self? presentalert(title "error", message "failed to save author \\(error message)") 194 } 195 } 196 } 197 } 198 }sw для получения дополнительной информации об этом шаге вы можете перейти к https //www back4app com/docs/ios/parse swift sdk/data objects/swift crud database operations 3 настройка отношений перед тем как начать создавать отношения, ознакомьтесь с https //www back4app com/docs/ios/parse swift sdk/data objects/relationships#quick reference для того, чтобы понять, какие объекты мы хотим связать друг с другом на рисунке ниже мы показываем, как эти объекты связаны как видно, отношения создаются путем размещения книги книги объекта посередине стрелки показывают, как каждый объект связан с книгой книгой объектом 4 реализация отношений случай 1 1 добавление 1 1 отношений можно легко осуществить, добавив свойство в книгу книгу , т е 1 struct book parseobject { 2 3 4 var isbn isbn? // esablishes a 1 1 relation between book and isbn 5 6 7 } в этом случае, книга книга и isbn isbn имеют отношение 1 1 где книга книга идентифицируется как родитель, а isbn isbn как ребенок внутри, когда back4app сохраняет экземпляр книга книга , он сначала сохраняет объект isbn isbn (под именем класса isbn isbn ) после завершения этого процесса back4app продолжает с объектом книга книга новый книга книга объект сохраняется таким образом, что его isbn isbn свойство представлено объектом pointer\<isbn> pointer\<isbn> объект pointer<> pointer<> позволяет нам хранить уникальный экземпляр объекта isbn isbn связанного с его соответствующим родителем случай 1\ n для 1\ n отношений наиболее эффективный способ их реализации это использование объекта parserelation\<book> parserelation\<book> parseswift предоставляет набор методов для добавления таких типов отношений для любого объекта, соответствующего протоколу parseobject parseobject например, если мы хотим создать 1\ n 1\ n отношение между book book и author author мы можем использовать 1 let somebook book 2 let authors \[author] 3 4 5 // we create a relation (identified by the name 'authors') between somebook and a set of authors 6 let booktoauthorsrelation = 7 guard let booktoauthorsrelation = try somebook relation? add("authors", objects authors) // book > author 8 else { 9 fatalerror("failed to add relation") 10 } 11 12 let savedrelation = try booktoauthorsrelation save() // saves the relation synchronously 13 14 booktoauthorsrelation save { result in // saves the relation asynchronously 15 // handle the result 16 } просто адаптировать этот фрагмент для других отношений, которые у нас есть для книга книга \ собираем все вместе как только мы установили основную идею реализации отношений, мы теперь завершаем savebook() savebook() метод мы перечисляем ключевые моменты, которые нужно иметь в виду в процессе 1 extension maincontroller { 2 /// collects the data to save an instance of book on your back4app database 3 func savebook() { 4 5 // 1 first retrieve all the information for the book (booktitle, isbnvalue, etc) 6 7 8 // since we are making multiple requests to back4app, it is better to use synchronous methods and dispatch them on the background queue 9 dispatchqueue global(qos background) async { 10 do { 11 let isbn = isbn(value isbnvalue) // 2 instantiate a new isbn object 12 13 let savedbook = try book( // 3 instantiate a new book object with the corresponding input fields 14 title booktitle, 15 publishingyear publishingyear, 16 genre genre, 17 isbn isbn 18 ) save() // 4 save the new book object 19 20 // 5 add the corresponding relations for new book object 21 guard let booktoauthorsrelation = try savedbook relation? add("authors", objects authors), // book > author 22 let bootktopublishersrelation = try savedbook relation? add("publishers", objects publishers), // book > publisher 23 let genrerelation = try genre relation? add("books", objects \[savedbook]) // genre > book 24 else { 25 return dispatchqueue main async { 26 self presentalert(title "error", message "failed to add relations") 27 } 28 } 29 30 // 6 save the relations 31 = try booktoauthorsrelation save() 32 = try bootktopublishersrelation save() 33 = try genrerelation save() 34 35 dispatchqueue main async { 36 self presentalert(title "success", message "book saved successfully ") 37 } 38 } catch { 39 dispatchqueue main async { 40 self presentalert(title "error", message "failed to save book \\((error as! parseerror) message)") 41 } 42 } 43 } 44 } 45 46 47 } 5 запрос отношений для 1 1 отношений, учитывая родительскую книгу книгу и её дочерний isbn isbn , мы запрашиваем соответствующий дочерний элемент, включая его в запрос книги книги 1 let query = book query() include("isbn") 2 3 let books = try query find() // retrieves synchronously all the books together with its isbn 4 5 query find { result in // retrieves asynchronously all the books together with its isbn 6 // handle the result 7 } 8 с этим все книги из query также будут иметь свойство isbn правильно установленное с соответствующим isbn объектом с другой стороны, для того чтобы извлечь объекты с 1\ n отношением, протокол parseobject предоставляет статический метод queryrelation( ,parent ) указывая имя отношения (в качестве первого параметра) и родителя, этот метод позволяет нам создать необходимый запрос например, чтобы извлечь всех author ’s, связанных с конкретной book мы можем использовать следующий фрагмент 1 let book book // book from which we are trying to retrieve its related authors 2 3 do { 4 let authorsquery = try author queryrelations("authors", parent book) // 'authors' is the name of the relation it was saved with 5 6 authorsquery find { \[weak self] result in 7 switch result { 8 case success(let authors) 9 self? authors = authors 10 11 dispatchqueue main async { 12 // update the ui 13 } 14 case failure(let error) 15 dispatchqueue main async { 16 self? presentalert(title "error", message "failed to retrieve authors \\(error message)") 17 } 18 } 19 } 20 } 21 } catch { 22 if let error = error as? parseerror { 23 presentalert(title "error", message "failed to retrieve authors \\(error message)") 24 } else { 25 presentalert(title "error", message "failed to retrieve authors \\(error localizeddescription)") 26 } 27 } аналогично, мы можем запрашивать другие связанные объекты, такие как publisher в файле bookdetailscontroller swift мы реализуем эти запросы для отображения связи книги с авторами и издателями 1 // bookdetailscontroller swift file 2 class bookdetailscontroller uitableviewcontroller { 3 4 5 /// retrieves the book's details, i e , its relation with authors and publishers 6 private func fetchdetails() { 7 do { 8 // constructs the relations you want to query 9 let publishersquery = try publisher queryrelations("publishers", parent book) 10 let authorsquery = try author queryrelations("authors", parent book) 11 12 // obtains the publishers related to book and display them on the tableview, it presents an error if happened 13 publishersquery find { \[weak self] result in 14 switch result { 15 case success(let publishers) 16 self? publishers = publishers 17 18 // update the ui 19 dispatchqueue main async { 20 self? tableview\ reloadsections(indexset(\[section publisher rawvalue]), with none) 21 } 22 case failure(let error) 23 dispatchqueue main async { 24 self? presentalert(title "error", message "failed to retrieve publishers \\(error message)") 25 } 26 } 27 } 28 29 // obtains the authors related to book and display them on the tableview, it presents an error if happened 30 authorsquery find { \[weak self] result in 31 switch result { 32 case success(let authors) 33 self? authors = authors 34 35 // update the ui 36 dispatchqueue main async { 37 self? tableview\ reloadsections(indexset(\[section author rawvalue]), with none) 38 } 39 case failure(let error) 40 dispatchqueue main async { 41 self? presentalert(title "error", message "failed to retrieve authors \\(error message)") 42 } 43 } 44 } 45 } catch { // if there was an error during the creation of the queries, this block should catch it 46 if let error = error as? parseerror { 47 presentalert(title "error", message "failed to retrieve authors \\(error message)") 48 } else { 49 presentalert(title "error", message "failed to retrieve authors \\(error localizeddescription)") 50 } 51 } 52 } 53 54 55 } 6 запустите приложение! перед нажатием кнопки запуска на xcode xcode , не забудьте настроить ваше back4app back4app приложение в классе appdelegate appdelegate ! вам нужно добавить пару жанров , издателей и авторов перед добавлением новой книги затем вы можете начать вводить информацию о книге, чтобы сохранить её в вашей базе данных back4app как только вы сохраните одну книгу, откройте вашу https //parse dashboard back4app com/apps и перейдите к вашему приложению, связанному с проектом xcode в разделе база данных вы найдете класс книга книга , где хранятся все книги, созданные приложением ios ios кроме того, вы можете увидеть, что back4app автоматически создал класс isbn isbn для связи с соответствующим объектом книга книга если вы вернетесь к классу книга книга , вы сможете определить типы данных для каждого типа связи в случае isbn isbn и жанр жанр , тип данных — это pointer<> pointer<> с другой стороны, для связей, таких как автор автор и издатель издатель , тип данных — это relation<> relation<> это ключевое различие, которое следует учитывать при построении связей