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
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?
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.
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.
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.
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")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With