4

I have BaseMO core data entity:

extension BaseMO {

    @NSManaged public var id: String
    @NSManaged public var mobileLocalId: String?
    @NSManaged public var pendingToSave: NSNumber?

}

What I want to achieve is kind of didSet var feature for @NSManaged:

extension BaseMO {

@NSManaged public var id: String {
  didSet {
    if (self.id.contains("<x-coredata://")) {
      fatalError()
    }
  }

@NSManaged public var mobileLocalId: String?
@NSManaged public var pendingToSave: NSNumber?

}

Each my NSManagedObjects object are subclassed of this parent BaseMO object. So eachtime I map (import) objects to credata I want to be sure that id does not contain <x-coredata://

I found answer here, but not sure how to use it.

Matrosov Oleksandr
  • 25,505
  • 44
  • 151
  • 277

1 Answers1

4

This is probably a good place to use a custom accessor.

In CoreData, this can be accomplished by using primitives (each attribute has an underlying primitive value). Just be sure to always implement calls in the getter and setter as below to keep key value observations firing correctly.

The CoreData Programming guide used to have more details on this if memory serves me correctly, but you can refer to Apple's documentation on primitives and proper book-keeping of custom accessors linked above for more info.

Using this, your code can be adjusted for your specific use case, but would end up looking something like:

public class BaseMO: NSManagedObject {

    @NSManaged fileprivate var primitiveId: String

    @objc public var id: String {
        get {
            willAccessValue(forKey: #keyPath(BaseMO.id))
            let value = primitiveId
            didAccessValue(forKey: #keyPath(BaseMO.id))
            return value
        }
        set {
            if (newValue.contains("<x-coredata://")) {
                fatalError()
            }
            willChangeValue(forKey: #keyPath(BaseMO.id))
            primitiveId = newValue
            didChangeValue(forKey: #keyPath(BaseMO.id))
        }
    }
}

eeekari
  • 202
  • 2
  • 7