Best way to query references in CloudKit?

杀马特。学长 韩版系。学妹 提交于 2020-01-01 11:14:17

问题


Say I have 2 entities in my CloudKit database:

- Album
  - (NSString) title

- Photo
  - (NSString) name
  - (CKRefrence) album

Photos have a CKReference to an Album. This means that 1 album can have many photos (as expected).

I have a screen where I want to display all albums, and how many photos are in each album. What is the best way to query for this? If I query for Albums right now, each album knows nothing about its photos.


回答1:


For each of the album object anAlbum, you would form your predicate and query the Photo record type like so:

let predicate = NSPredicate(format: "album == %@", anAlbum)
let query = CKQuery(recordType: "Photo", predicate: predicate)

In the completionHandler, you can get a count of the result array, which would be the number of Photos belonging to anAlbum.




回答2:


CloudKit is not supposed to be used as model layer, it is just connectivity framework, which provides you with database. You can use CoreData as model layer to solve your task. Create album entity, which have one to many relationship to photo entity, which has one to one relationship to album.

Then retrieve all albums first and map each record to corresponding Album entity in CoreData. Then get all photos, map them to Photo entity in CoreData and for each photo match corresponding Album entity in CoreData.



来源:https://stackoverflow.com/questions/24788415/best-way-to-query-references-in-cloudkit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!