Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 472
David Barta Avatar asked Jun 04 '15 06:06

David Barta


People also ask

What is persistent store in core data?

A persistent store is a repository in which managed objects may be stored. You can think of a persistent store as a database data file where individual records each hold the last-saved values of a managed object. Core Data offers three native file types for a persistent store: binary, XML, and SQLite.

What is scalar type core data?

Scalar Types Core Data has support for many common data types like integers, floats, booleans, and so on. However, by default, the data model editor generates these attributes as NSNumber properties in the managed object subclasses.

What is NSManaged?

NSmanaged is subclass of NSObject. @NSManaged means extra code will be given to these props at runtime. It tracks the changes made to those properties.


1 Answers

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")
    }
}
like image 175
Tom Harrington Avatar answered Sep 21 '22 17:09

Tom Harrington