Search code examples
iosobjective-cnsmutabledictionarykey-value-observingkvc

NSMutableDictionary setValue:forUndefinedKey


I'm developing an iOS app. I have a class that extends NSObject that defines 1 property

//.h file
@property (nonatomic,retain) NSMutableDictionary *livedata; 


//.m file
if(self = [super init]){
    self.livedata = [[NSMutableDictionary alloc] init];
    [self.livedata setValue:@"myvalue" forUndefinedKey:@"myUndefinedKey"];
}

I'm getting this error. * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key myUndefinedKey.'

I've used NSMutableDictionary in the past for kvc, kvo. Yes I see the class is not kvc compliant.


Solution

  • The problem is that you're calling a method that raises an exception when it is called. setValue:forUndefinedKey: is only called when setValue:forKey:, quoting this article, finds no property for a given key. Instead, just call

    [self.livedata setValue:@"myvalue" forKey:@"myKey"];