我在我的应用中使用CoreData将数据加载到UITableView中。如果我运行此代码段,应用程序崩溃:
frontExec
这是我用来将数据加载到tableView中的部分:
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as NSManagedObject
newManagedObject.setValue("Test String", forKey: "markedCell")
崩溃线:let context = self.fetchedResultsController.managedObjectContext
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
var taskString:NSString
taskString = object.valueForKey("name") as String
cell.textLabel!.text = object.valueForKey("name") as? String
var request:NSFetchRequest = NSFetchRequest(entityName: "Person")
request.predicate = NSPredicate(format:"markedCell = %@", taskString)
var results : [NSManagedObject] = context.executeFetchRequest(request, error: nil) as [NSManagedObject]
if (results.count > 0) {
//Element exists
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
else {
//Doesn't exist
cell.accessoryType = UITableViewCellAccessoryType.None
}
错误消息:taskString = object.valueForKey("name") as String
如果我使用上面剪切的第一个代码,我就会崩溃。如果我不使用此代码,该应用程序运行正常。我真的不知道为什么它崩溃/某些价值是fatal error: unexpectedly found nil while unwrapping an Optional value
。
答案 0 :(得分:0)
用
替换var taskString:NSStringif let taskString = object.valueForKey("name") as? String {
cell.textLabel!.text = taskString
// rest of your code
}
你的应用程序崩溃也是因为object.valueForKey(" name")不是String,即没有返回值。