Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to query references in CloudKit?

Tags:

ios

cloudkit

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.

like image 344
user1007895 Avatar asked Jul 16 '14 18:07

user1007895


2 Answers

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.

like image 91
Denis Avatar answered Nov 09 '22 08:11

Denis


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.

like image 27
Alex Avatar answered Nov 09 '22 07:11

Alex