swiftcore-datansmanagedobject

Making an "NSManaged public var" an Optional Boolean


How can I make an NSManaged public var an optional boolean? When I type the following:

import Foundation
import CoreData
import UIKit

extension SomeClass {

    @NSManaged public var isLiked: Bool?
    @NSManaged public var isDisliked: Bool?

}

I get the error:

Property cannot be marked @NSManaged because its type cannot be represented in Objective-C

What I want is a property that can be neither liked or disliked.


Solution

  • If you use @NSManaged, you have to follow its rules. Those rules include working with ObjC, which doesn't have optionals. But you don't have to use @NSManaged, even when using Core Data. You can drop it as long as you implement your own accessors. Something like:

    public var isLiked : Bool? {
        get {
            willAccessValue(forKey: "isLiked")
            let isLiked = primitiveValue(forKey: "isLiked") as! Int64
            didAccessValue(forKey: "isLiked")
            return isLiked
        }
        set {
            willChangeValue(forKey: "isLiked")
            setPrimitiveValue(newValue, forKey: "isLiked")
            didChangeValue(forKey: "isLiked")
        }
    }