iosobjective-ccloudkitckreference

CloudKit - Storing multiple CKReferences in a CKRecord


In my app, I have a Record type (UserActivity) which just stores images a user wants to save to their profile. This record type only contains a single attribute - a CKReference to another record type (RecordTypeA for example). It works perfectly...I'm able to store and retrieve the data via the references to construct the images and display it appropriately on screen. However, I just realized I need to add a second attribute to the UserActivity record type, which will be a CKReference to a different record type (call it RecordTypeB). Record type B is a second kind of image that needs to be separately identified. So each row in UserActivity will now have 1 of 2 possible CKReferences, but not both.

I can save the new RecordTypeB reference with no problem, but I have a couple of issues as a result. First, when I save it, whether through code or CKDashboard, the record now shows the title as "No Name" because there is nothing for the attribute for RecordTypeA. Originally, the record names would be ref:followed-by-recordid. It works as it did originally if the UA record has a reference to RecordTypeA. So is there a way to make it create the record name for RecordTypeB reference only? Is it possible that I should change this to a CKReference List now that I have a 2nd attribute? Secondly, and more importantly, when I'm retrieving UserActivity records, how can I tell for a given record if it contains a reference to RecordTypeA or RecordTypeB? Is there a way similar to the isKindOfClass method? In this case, that method just shows it's a CKReference and not what record type it's a reference to. And maybe the second question would be automatically solved if the CKReference List is the appropriate solution? Thanks in advance for the guidance!


Solution

  • Experience shows that the title of the record will be the first field that you created for that recordType. I haven't found any documentation about this so it could be a coincidence. If you want your title be the RecordTypeB field, then recreate your recordType and then first create RecordTypeB. There is no other way to influence what the title will be.

    You could change it to a CKReference List, but i think in your case it would be easier to keep the 2 separate fields. Only when you don't mind what item is what then you should use a list. But in your case the references are 2 different types.

    If you did not write one of the fields, then when you read the record and look at the reference, then it should be nil. You can't ask the recordType of a CKReference. But if you create a field for a reference, then you know what recordType it should be. Otherwise you need to create an extra field for indicating what recordType it is.