How to fetch reference string from CKReference object

2.1k views Asked by At

I have two record type: Books & Authors. Books have two attribute BookName(String) & AuthorName(CKReference). Authors have one attribute AuthorTitle(String).

I save CKReference as follows

let authorReference = CKReference(record: addBookViewController.authorTitle!, action: CKReferenceAction.DeleteSelf)

bookRecord.setObject(authorReference, forKey: "AuthorName")

I am currently fetching CKReference as follows to display on table

let authorReference = bookRecord.objectForKey("AuthorName") as! CKReference

let authorTitle = authorReference.recordID.recordName

cell.detailTextLabel?.text = authorTitle

On tableview cell it shows record ID of AuthorName. Instead I want to see AuthorName in string format. How do I get it?

2

There are 2 answers

1
Edwin Vermeer On BEST ANSWER

Your AuthorName field is a reference to an other record. In order to get data from that record, you need to fetch it first.

database.fetchRecordWithID(CKRecordID(recordName: authorReference.recordID), completionHandler: {record, error in
 // now you can use record.objectForKey("AuthorTitle")
}
0
Nazarii Stadnytskyi On

You can also use CKFetchRecordsOperation

CKRecordID *recordID = [[CKRecordID alloc] initWithRecordName:@"firstRecordIDName"];
CKRecordID *recordID2 = [[CKRecordID alloc] initWithRecordName:@"secondRecordIDName"];
NSArray *arrayOfRecordIDs = @[recordID,recordID2];;
CKFetchRecordsOperation *fetchRecordsOperation = [[CKFetchRecordsOperation alloc]initWithRecordIDs:arrayOfRecordIDs];
fetchRecordsOperation.perRecordCompletionBlock = ^(CKRecord *record, CKRecordID *recordID, NSError *error) {
    if (error) {

        // handle error

    }else {

        // Successfull fetch, create data model

    }

};
fetchRecordsOperation.database = publicDatabase;
[fetchRecordsOperation start];