Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 787
alexjrlewis Avatar asked Jan 30 '23 21:01

alexjrlewis


1 Answers

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")
    }
}
like image 183
Tom Harrington Avatar answered Feb 05 '23 15:02

Tom Harrington