核心數據的新特性和我有兩個問題:正確初始化NSManagedObject
,並保留其在便利和指定初始值設定項之間的值。初始化核心數據管理對象
我在我的AnalyticsEvent NSManagedObject
子類代碼:
@NSManaged public var eventName: String?
@NSManaged public var type: String?
@NSManaged public var reference: String?
@NSManaged public var timestamp: Double
public required init() {
// Initialize CoreData stack...
let manager = CoreDataManager(modelName: "Analytics", storeName: "Analytics")
// I'm not sure what I should be using to instantiate a new entity here...
// I believe the entity(forEntityName:in:) class method should return an existing value stored in managedObjectContext...
let event = NSEntityDescription.entity(forEntityName: "Event", in: manager.managedObjectContext!)
// ... and insertNewObject(forEntityName:into:) to create a placeholder
// for my new object until I issue saveContext() on managedObjectContext.
// This isn't working right now, so comment out following line
//let event = NSEntityDescription.insertNewObject(forEntityName: "Event", into: database.managedObjectContext!) as! AnalyticsEvent
super.init(entity: event!, insertInto: database.managedObjectContext)
let customProperties = CustomProperties()
self.customPropertiesData = NSKeyedArchiver.archivedData(withRootObject: properties) as Data
self.timestamp = Date().timeIntervalSince1970
}
public convenience init(eventName: String) {
self.init()
// At this point the data set in my designated initializer (above),
// the values have been lost. For example, timestamp == 0
self.eventName = eventName
self.type = EventType.discreteEvent
}
謝謝!
編輯:
進一步調查可能會發現,也許我的便利初始化正在被super.init(entity:insertInto:)
調用來調用,如果是,我不知道它是怎麼找到的便利初始化的選擇...但它會解釋爲什麼它的值(如時間戳)沒有被保留 - 因爲它是對象的新實例?!嗯......
編輯2:
我忘了說我得到這個運行時錯誤當執行到行:
self.eventName = eventName
CoreData:錯誤:變異託管對象0x7fa2da54da90(0x7fa2da54da40 )在它從上下文中移除之後。
謝謝,但我也試過。沒有運氣!它也提供相同的運行時錯誤。 –
@AlexSmith我正在研究初始化器和'@ NSManaged'實際上現在意味着什麼...你見過這個答案:http://stackoverflow.com/a/39239651/1060154我不能擔保它,但會快速嘗試! – MathewS
再次感謝,但不幸的是不是我所需要的。和以前一樣... –