0

Adding attribute to entity which don't exist in XCDataModel was easily accomplised VIA @synthesize and @dynamic in objective c. Please guide how to achieve this in swift.

@NSManaged public var salesPrice: NSNumber?
public var totalVal: NSNumber {
   get {
       return salesPrice ?? NSNumber(value: 0)
   }
}

Here sales price is managed but totalVal is not managed nor exist in xcDataModel. I am getting crash 'The entity is not key value coding-compliant for the key 'totalVal' on accessing totalVal.

if let coreObj = indItem.parentObj.value(forKey: keyPath) { }

Crash happening here.

  • 'indItem.parentObj' this is right object (I double checked)
  • 'keyPath' is 'totalVal' (I copied it rightly)
Aaban Tariq Murtaza
  • 1,155
  • 14
  • 16
  • 1
    Please show the code where you are accessing `totalVal`, there is no problem with the code you have currently shown. It sounds like you're accessing totalVal using something like a sort descriptor or other key-value coding accessor – jrturton Jan 03 '22 at 10:38
  • Thanks for your time. I updated question. Crashing code is present in question. – Aaban Tariq Murtaza Jan 03 '22 at 13:03
  • 1
    I assume you have to use `value(forKey:)` because you don't know the property you're looking for at runtime? So you can't just do `parentObj.totalVal`? – jrturton Jan 03 '22 at 14:20
  • Can't you do `indItem.parentObj.totalVal `? – Willeke Jan 03 '22 at 14:25
  • 1
    See [Swift optional property using KVC causes crash](https://stackoverflow.com/a/31353182) – Willeke Jan 03 '22 at 14:28
  • @Willeke, as jrturton mentioned. Property will be decided at runtime. So direct attribute can't be addressed. – Aaban Tariq Murtaza Jan 03 '22 at 14:37

1 Answers1

1

To support key-value coding for a type declared in Swift, you have to mark it with the @objc keyword:

@objc public var totalVal: NSNumber {
jrturton
  • 118,105
  • 32
  • 252
  • 268