iosdatabasecloudkitckrecordckreference

Fetch a CKReference object from a CKReference


I have 3 records types which contained attributes like this :

Client

Username : String

ProfilImage : UIImage

Comment

User : Client Reference

Message : String

Shop

Comments : Comment Reference List

Can I fetch the client Username and ProfilImage from a Shop CKRecord object ? Can I do this path :

  1. Fetch the comments references from a Record of Shop
  2. Fetch the user reference from each comment reference found
  3. And finally fetch the username and profil from the user reference of comment reference of shop record

If there's a path, what's the best way to do this ?


Solution

  • Here is example for Step 1. The other steps would follow similarly from the steps you've listed, cascading on the results of each previous step. (NOTE: There is no need for the explicit CKReference fields since they can be gleaned from the CKRecord variables, but I wanted to make the example more readable)

    struct Shop {
      // other variables....
      var record : CKRecord?
      var commentRef : CKReference?
    }
    
    struct Comment {
      // other variables....
      var record : CKRecord?
      var clientRef : CKReference?
    }
    
    var shops : [Shop]
    var comments : [Comment]
    
    func commentsWithReference(ref: CKReference) -> [Comment] {
      let matchingComments = comments.filter {$0.record!.recordID == ref.recordID }
      return matchingComments
    }
    
    let shopComments = shops.map { commentsWithReference($0.commentRef!) }