CoreData Object为零

时间:2015-04-30 13:51:31

标签: ios swift core-data ios8 xcode6

我在我的应用中使用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

希望你能帮助我。谢谢你的回答!

1 个答案:

答案 0 :(得分:0)

替换var taskString:NSString
if let taskString = object.valueForKey("name") as? String {
    cell.textLabel!.text = taskString
    // rest of your code
}

你的应用程序崩溃也是因为object.valueForKey(" name")不是String,即没有返回值。

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html