Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Crashes when loading an empty attribute from Cloudkit - using Swift

I am trying to get access to a record value in CloudKit, here MyPin, it has a title & subtitle attribute/field value. However it may happen that sometimes the record value is empty(here subtitle), and it crashes at the line when I call:

var tempS: String = Annot["Subtitle"] as! String

because Annot["Subtitle"] doesn exist ...

When I do

println(Annot["Subtitle"]) 

it returns nil

but if I do :

if (Annot["Subtitle"] == nil) {
println("just got a nil value")
}

I never enter the if statement:

Can someone help me how to identify if the record has an empty value?

Here is my line of codes:

let container = CKContainer.defaultContainer()        
let publicData = container.publicCloudDatabase        
let query = CKQuery(recordType: "MyPin", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
publicData.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil { // There is no error
for Annot in results {
var tempS: String = Annot["Subtitle"] as! String
}}
like image 887
david thanoon Avatar asked Sep 26 '22 19:09

david thanoon


1 Answers

when you get Annot["Subtitle"] it will give you a CKRecordValue? return which has a base class of NSObjectProtocol. So in your case the field does exist but it's not a String so casting it using as! String will crash your app. Since the field exists the CKRecordValue will not be nil. However the content of that field is nil. When you print the field, it will output the .description of that field. In your case that is nil. Could you try this code instead:

if let f = Annot["Subtitle"] {
   print("f = \(f) of type \(f.dynamicType)")
}

then set a breakpoint on the print line and when it stops try the following three statements in your output window:

po Annot
po f
p f

After the po Annot you should see what's in that record. Including your subtitle field. The po f is not so interesting. It will just output a memory address. The p f however will show you the actual type. If it's a string you should see something like: (__NSCFConstantString *) $R3 = 0xafdd21e0

P.S. Maybe you should call it record instead of Annot. It's a local variable so it should start with a lower case character. And it's still a record and not an Annot.

like image 182
Edwin Vermeer Avatar answered Sep 30 '22 07:09

Edwin Vermeer