我将 Xcode 更新到 10.2.1 并注意到我无法在子 NSManagedObject 类中初始化和存储任何自定义属性(它在以前的 Xcode 版本中工作)。有人有同样的问题吗?
我创建了新项目。如果我将创建一个父实体和一个子实体。我只能将自定义数据存储在父实体中,但如果我将一些自定义类存储在子实体中,则该属性将始终为零。
这是父实体:
@objc(Entity)
public class Entity: NSManagedObject {
class var entityName: String {
return String(describing: self)
}
private var testClass = MyTestClass()
init() {
let entityName: String = type(of: self).entityName
let context: NSManagedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
guard let entityDescription: NSEntityDescription = NSEntityDescription.entity(forEntityName: entityName, in: context) else {
fatalError("Failed to create entity description for name: \(entityName)")
}
super.init(entity: entityDescription, insertInto: context)
print(testClass.testProperty)
}
}
extension Entity {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Entity> {
return NSFetchRequest<Entity>(entityName: "Entity")
}
@NSManaged public var title: String?
}
这是子实体:
@objc(EntityChild)
public class EntityChild: Entity {
private var testClassChild = MyTestClass()
override init() {
super.init()
print(testClassChild.testProperty)//on this line app will crash
}
}
extension EntityChild {
@nonobjc public class func fetchRequest() -> NSFetchRequest<EntityChild> {
return NSFetchRequest<EntityChild>(entityName: "EntityChild")
}
@NSManaged public var title2: String?
}
还附上代码执行的截图:
笔记
如果使用属性为lazy
或添加属性为强制解包并初始化它们,它会按预期工作init