'CoreData valueForKey issue on Xcode 13

I have an issue in a client's app where calls to valueForKey: on an NSManagedObject subclass are failing for particular CoreData properties when the app is built with Xcode versions >= 13.x. For some properties, a call like this (Object would be a subclass of NSManagedObject, with a property named 'propertyName'):

Object *object = ....
[object valueForKey:@"propertyName"]

results in a call to valueForUndefinedKey:, rather than returning the actual value for the property.

When the app is built with an earlier version of Xcode (I've tried with 12.5.1), it works fine, the value is returned as expected, without a call to valueForUndefinedKey:.

Has anybody seen behavior like this?



Solution 1:[1]

In case anybody runs into this, I did solve it. The problem was that the project was overriding the valueForKey: method of NSManagedObject in a really bizarre way. Basically, it had this:

@interface NSManagedObject (Ext)
@end
@implementation NSManagedObject (Ext)
- (id)valueForKey:(id)key {
  // do stuff
  [super valueForKey:key];
}
@end

That seems to work fine prior to Xcode 13 and iOS 15 (despite being a really bad thing to do), but now has unpredictable behavior. The solution was to just create a class that is a subclass of NSManagedObject, override that method in that new class, and make other classes be subclasses of that new class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1