简体   繁体   English

Swift + Xcode 6 beta 3 + Core Data = awakeFromInsert没有被调用吗?

[英]Swift + Xcode 6 beta 3 + Core Data = awakeFromInsert not called?

Need help. 需要帮忙。

I'm creating new Document-based Core Data Cocoa project. 我正在创建新的基于文档的Core Data Cocoa项目。 Add entity named 'Entity' into the core data model. 将名为“ Entity”的实体添加到核心数据模型中。 Add 'creationDate' propery into it and set its type as Date. 向其中添加“ creationDate”属性,并将其类型设置为Date。 And create NSManagedObject subclass from 'Editor' menu. 然后从“编辑器”菜单创建NSManagedObject子类。

Now I add into 'Entity.swift' file this code: 现在,将以下代码添加到“ Entity.swift”文件中:

override func awakeFromInsert()  {
    super.awakeFromInsert()
    self.creationDate = NSDate()
    println("awakeFromInsert called")
}

Now in my NSPersistentDocument subclass I write such a init() method: 现在在我的NSPersistentDocument子类中,编写这样的init()方法:

init() {
    super.init()

    var context = self.managedObjectContext
    context.undoManager.disableUndoRegistration()
    var entity = NSEntityDescription.insertNewObjectForEntityForName("Entity", inManagedObjectContext: context)
    context.processPendingChanges()
    context.undoManager.enableUndoRegistration()

    println("\(entity)")
}

Everything compiles... BUT awakeFromInsert is never called! 一切都会编译...但是永远不会调用awakeFromInsert! The interesting part is that 'entity' object ain't nil! 有趣的是,“实体”对象不是零! It was created, but not initialized. 它已创建,但尚未初始化。 And if I write this line in init method 如果我在init方法中编写此行

entity.creationDate = NSDate()

then creationDate property will be set to a current date as expected. 然后creationDate属性将按预期设置为当前日期。

But that's not all. 但这还不是全部。 If I debug execution step-by-step I can see that execution enters 'Entity.swift' file, but starts from the top of the file, then immediately drops and returns back to the NSPersistentDocument subclass file. 如果我逐步调试执行,我可以看到执行进入了“ Entity.swift”文件,但从文件的顶部开始,然后立即删除并返回到NSPersistentDocument子类文件。

Tell me, is it a bug? 告诉我,这是一个错误吗? Because I'm tired to fight with this nonsense. 因为我厌倦了与这种胡说八道。 Thanks. 谢谢。

Accidentally I got it work: you have to add @objc(YourSubclass) before subclass declaration. 偶然我得到了它:您必须在子类声明之前添加@objc(YourSubclass)。 I usually did @objc class MySubclass and turned out it does not work (don't know why). 我通常使用@objc类MySubclass,结果发现它不起作用(不知道为什么)。

WORKING: 工作方式:

@objc(YourSubclass)
class YourSubclass : NSManagedObject {
...

NOT WORKING: 不工作:

@objc class YourSubclass : NSManagedObject {
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM