我有一个继承自NSManagedObject
的类:
import Foundation
import CoreData
class Note: NSManagedObject {
@NSManaged var text: String
@NSManaged var name: String
init(name: String, text:String, context: NSManagedObjectContext){
let entity = NSEntityDescription.entityForName("Note", inManagedObjectContext: context);
super.init(entity: entity!, insertIntoManagedObjectContext: context)
self.text = text
self.name = name;
}
}
当我创建这些实例时,一切都正常,但当我搜索这些实体时,我会收到一个非常奇怪的错误:
fatal error: use of unimplemented initializer 'init(entity:insertIntoManagedObjectContext:)'
这是导致错误的代码:
func coreDatePlayground(){
var note = Note(name: "A new note", text: "blah", context: self.managedObjectContext!)
println("\(note.name) \(note.text)")
var noote2 = Note(name: "Another note", text: "blah blah", context: self.managedObjectContext!)
managedObjectContext?.save(nil)
var fetch = NSFetchRequest(entityName: "Note")
// This line causes the crash.
var results = self.managedObjectContext?.executeFetchRequest(fetch, error: nil)
if let objects = results{
println(objects.count)
}
}
我发现通过将初始化程序更改为convenience类型,并在self上调用而不是在super上调用可以解决这个问题,但我不知道为什么。
convenience init(name: String, text:String, context: NSManagedObjectContext){
let entity = NSEntityDescription.entityForName("Note", inManagedObjectContext: context);
self.init(entity: entity!, insertIntoManagedObjectContext: context)
self.text = text
self.name = name;
}
上面的代码可以运行,但我不知道为什么。有人知道发生了什么吗?是一个错误还是我的问题?