当我尝试使用Swift从iCloud加载数据时,应用程序崩溃时出现此错误。这是为什么?我似乎无法找到这个错误?
代码:
func LoadEvents() {
let predicate:NSPredicate = NSPredicate(value: true)
let query:CKQuery = CKQuery(recordType: "Data", predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
if let database = self.publicDatabase {
database.performQuery(query, inZoneWithID: nil, completionHandler: { (records:[AnyObject]!, error:NSError!) in
if error != nil {
self.alert("Error: \(error.localizedDescription)", Message: "Make sure iCloud is turned on and you are connected to the internet")
} else {
dispatch_async(dispatch_get_main_queue()) {
self.EventsArray.removeAll(keepCapacity: false)
for record in records {
let usernameRecord:CKRecord = record as CKRecord
self.EventsArray.insert(usernameRecord.objectForKey("Events") as String, atIndex: 0)
println("1")
}
//update data
self.collectionView.reloadData()
}
}
})
}
}
答案 0 :(得分:3)
您正在阅读的记录可能没有名为Events的字段。所以objectForKey将返回nil,它不能被转换为字符串。您可以使用as? String
或使用:
if let event = usernameRecord.objectForKey("Events") as? String{
self.EventsArray.insert(event, atIndex: 0)
}