David Barta
David Barta

Reputation: 346

Core data Int16 as optional

  1. In Swift, how do you make an NSManaged Int16 property be optional like this:

    NSManaged var durationType: Int16?

    I'm getting compiler error: roperty cannot be marked @NSManaged because its type cannot be represented in Objective-C

  2. If this is not possible, and I check the optional box in the Core Data model editor, how do I then check if this property has a value when coming from the database?

Upvotes: 8

Views: 2514

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70986

You can make the property optional and keep it Int16. The key is that @NSManaged is not required, but if you remove it, you must implement your own accessor methods.

One possible implementation:

var durationType: Int16?
    {
    get {
        self.willAccessValueForKey("durationType")
        let value = self.primitiveValueForKey("durationType") as? Int
        self.didAccessValueForKey("durationType")

        return (value != nil) ? Int16(value!) : nil
    }
    set {
        self.willChangeValueForKey("durationType")

        let value : Int? = (newValue != nil) ? Int(newValue!) : nil
        self.setPrimitiveValue(value, forKey: "durationType")

        self.didChangeValueForKey("durationType")
    }
}

Upvotes: 4

Related Questions