-3

My app is crashing when I try to set value in NSMutableDictionary.

Here is the code below which demostrate the crash, I am not able to find out any crash log also in the console.

NSArray *b =[[a objectAtIndex:1] valueForKey:@"value"];
NSMutableDictionary *b1 =[b objectAtIndex:0];
NSString *str = self.tes;
[b1 setValue:str forKey:@"value"];

Please help me regarding this.

b1 Dictionary log

{
    question = "vale";
    type = a;
}
Popeye
  • 11,839
  • 9
  • 58
  • 91
Gaurav Parmar
  • 447
  • 2
  • 11

2 Answers2

4

setValue:forKey: is part of the NSKeyValueCoding protocol, which among other things, lets you access object properties from the likes of Interface Builder. setValue:forKey: is implemented in classes other than NSDictionary.

setObject:forKey: is NSMutableDictionary's reason to exist. Its signature happens to be quite similar to setValue:forKey:, but is more generic (e.g. any key type).

So in your case just replace all setValue:forKey with setObject:forKey and valueForKey: with objectForKey:

--

Difference between objectForKey and valueForKey?

Community
  • 1
  • 1
arturdev
  • 10,884
  • 2
  • 39
  • 67
  • Using `setValue:forKey:` is actualy safer, because it handles `nil` values by removing the key. On the other side, `setObject:forKey:` would throw exception and probably crash the app. – Tricertops Jul 17 '15 at 06:48
  • I prefer to handle `nil` values rather than collect a strange bugs :) – arturdev Jul 17 '15 at 07:01
  • What bugs? It’s defined and documented behavior of `NSMutableDictionary`. Also makes sense: if you set `nil` for `@"key"`, then getting value for `@"key"` should be `nil` (non-existent). – Tricertops Jul 17 '15 at 07:09
0

So you said you are getting EXC_BAD_ACCESS crash. Try turning on Zombies in Xcode’s Scheme editor. See Enable and Debug Zombie objects in iOS using Xcode 5.1.1. That question explains how to use it, but you don’t need to run Instruments as mentioned there.

Then just run the app and Xcode will show you the reason of EXC_BAD_ACCESS. Don’t forget to turn Zombies off after you don’t need it.

The name Zombie comes from the fact that under this mode all deallocated objects will be marked and will be kept as special regions of memory (not live, not dead, zombies). Once your code attempts to use such deallocated object, Xcode will notice and print helpful message.

Community
  • 1
  • 1
Tricertops
  • 8,492
  • 1
  • 39
  • 41