尝试将字符串添加到Core Data时,我收到标题错误。这是我的代码:
func save(name: String) {
let model = CoreDataModel(modelName: modelName, modelBundle: modelBundle!, storeType: .SQLite(DocumentsDirectoryURL()))
let factory = CoreDataFactory(model: model)
let context = factory.createContext()
let entity = NSEntityDescription.entityForName("Transaction", inManagedObjectContext: context)
let transaction = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: context)
transaction.setValue(name, forKey: "name")
do {
try context.save()
transactions.append(transaction)
}catch let error as NSError {
print(error)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
let transaction = transactions[indexPath.row]
print(transaction)
cell!.textLabel!.text = transaction.valueForKey("name") as? String
return cell!
}
错误在这一行:
cell!.textLabel!.text = transaction.valueForKey("name") as? String
这是完整的错误描述:
<NSManagedObject: 0x7f9d5c216a90> (entity: <null>; id: 0xd000000000040000 <x-coredata://442A125F-AB41-4CA3-AAA5-A5C59840D5EE/Transaction/p1> ; data: <fault>)
2016-04-13 19:25:29.207 Project1[22981:2242560] *** -[NSEntityDescription _entityClass]: message sent to deallocated instance 0x7f9d5c2089e0
任何人都知道我为什么会这样做?
答案 0 :(得分:0)
似乎问题是我在本地创建NSManagedObjectContext
以保存(),我必须将前3行移动到ViewDidLoad
,并将context
声明为类成员。
This线程帮助我解决了问题。