0

I'm trying to set a value in an NSMutableDictionary but I'm always getting this error:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDictionaryI 0x10fd55990> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key image.'

In the NSMutableDictionary I have an @"image" field that can be null. I want to replace the null value with a placeholder image name. This is how I do it:

NSMutableDictionary * item = self.carouselSource[index];
if([Utils isNull:[item valueForKey:@"image"]]) {
[item setValue:@"default_image.png" forKey:@"image"]; 
}

But the application crash in this line

[item setValue:@"default_image.png" forKey:@"image"];

due to the error above.

Ne AS
  • 1,490
  • 3
  • 26
  • 58
  • Use `fast enumration` – Anurag Sharma Aug 11 '17 at 10:58
  • 6
    Your dictionary is immutable - it's an `NSDictionary` and not an `NSMutableDictionary`. for more information you can get from [here](https://stackoverflow.com/questions/14731353/nsdictionaryi-setobjectforkey-unrecognized-selector-sent-to-instance) – Anbu.Karthik Aug 11 '17 at 10:58
  • @Anbu.Karthik check my edit please – Ne AS Aug 11 '17 at 11:02
  • @Llg - can you update the question based on `NSMutableDictionary` modification – Anbu.Karthik Aug 11 '17 at 11:03
  • @Anbu.Karthik I edited my question please check it – Ne AS Aug 11 '17 at 11:17
  • 1
    try this `NSMutableDictionary * item = [self.carouselSource[index] mutableCopy];` – Anbu.Karthik Aug 11 '17 at 11:19
  • @Llg - problem solved or not my bro/sister – Anbu.Karthik Aug 11 '17 at 11:29
  • @Anbu.Karthik thank you so much it works! Can you please make it as an answer and explain why it works with the `mutableCopy`? Thanks again! – Ne AS Aug 11 '17 at 11:32
  • 1
    Don't use `valueForKey: / setValue:forKey` unless you can explain why you explicitly need KVC in this case. Can you? That would also avoid this misleading error message (but not the error per se). – vadian Aug 11 '17 at 11:37
  • @Llg - check the updated answer – Anbu.Karthik Aug 11 '17 at 11:38
  • `NSMutableDictionary * item = self.carouselSource[index];` That's a cast, it doesn't transform a `NSDictionary` into a `NSMutableDictionary`. You can use `mutableCopy`, or call the init method: `initWithDictionary:` if your objects are not NSCopying compliant. – Larme Aug 11 '17 at 15:32

1 Answers1

0

Your dictionary is immutable - it's an NSDictionary and not an NSMutableDictionary.if you want to convert any(array, dictionary) immutable to mutable use mutableCopy for full conversion(balance the retain count).

NSMutableDictionary * item = [self.carouselSource[index] mutableCopy];
if([Utils isNull:[item objectForKey:@"image"]]) {
[item setObject:@"default_image.png" forKey:@"image"]; 
 }

instead of

 NSDictionary * item = self.carouselSource[index];
if([Utils isNull:[item valueForKey:@"image"]]) {
[item setValue:@"default_image.png" forKey:@"image"]; 
}
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143