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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With