将原语分配给NSManagedObject实例(Swift)

时间:2015-07-25 16:25:04

标签: objective-c swift core-data primitive swift2

我无法在故事板中完成这项工作:

设置

// Extract an int from a (JSON) dictionary
let dict = ["eventId" : NSNumber(int:20)] as [String: AnyObject]
let eventId = dict["eventId"] as? Int

// Create managed object class
@objc(Event)
class Event : NSManagedObject {
  @NSManaged var eventId: Int16 // as generated by Xcode
}
var event = Event()

尝试将基元分配给Core Data对象失败

event.eventId = eventId! 
// Cannot assign a value of type 'Int' to a value of type 'Int16' 

event.eventId = Int16(eventId!)
// Execution was interrupted, reason: signal SIGABRT.

event.eventId = Int32(eventId!)
// Cannot assign a value of type 'Int32' to a value of type 'Int16' 

完整性测试

eventId == nil  // false
eventId == 0    // false
eventId!        // 20
Int32(eventId!) // 20, transforming into Int32 seems to work
Int16(eventId!) // 20, transforming into Int16 seems to work
eventId is Int  // true, but with weird warnings:
// Conditional cast from Int! to Int always succeeds
// 'is' test is always true
eventId is NSNumber // true, to my surprise! Only one warning:
// 'is' test is always true

更多详情

请注意,将字典对象强制转换为Int16Int32会返回nil 此外,使用let eventId = dict["eventId"]!.integerValue也会产生相同的结果 将id定义为Int32也无济于事,分配失败。

在具有完整Core Data堆栈的正确项目中,包括模型,上下文等,这种情况也是如此。

我有一种预感,它与指令@NSManaged生成访问器的方式有关,但我不知道如何在不编写更多代码的情况下修复它。

此外,当我有时从头开始创建一个带有Core Data的新项目时它才起作用 - 但我无法辨别出任何差异。如果您有任何见解,请告诉我。我通常的解决方法是不使用原语,但使用NSNumber有时不那么简洁。

1 个答案:

答案 0 :(得分:1)

NSManagedObject 的实例必须创建指定的实例 初始化

init(entity:insertIntoManagedObjectContext:)

否则将无法在运行时正确创建Core Data访问器方法。 所以这应该有效:

let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: context)!
let event = Event(entity: entity, insertIntoManagedObjectContext: context)

// Alternatively, use the equivalent "convenience method" from NSEntityDescription:
let event = NSEntityDescription.insertNewObjectForEntityForName("Entity", inManagedObjectContext: context) as! Event

event.eventId = Int16(eventId!)