10

OK, this is driving me nuts -- please tell me I'm not losing my mind!

I declare:

NSMutableDictionary* generalSettingsDict;

im my .h

I init:

generalSettingsDict = [[NSMutableDictionary alloc] initWithCapacity:5];

in a viewWillAppear

I set:

[generalSettingsDict setValue:[NSNumber numberWithBool:control.on]
                       forkey:[NSNumber numberWithInt:control.tag]];

in a method:

-(void)settingChanged:(UISwitch*)control forEvent:(UIEvent *)event

And I get "NSMutableDictionary may not respond to setValue:forkey:" and the app crashes when it is run.

Please help :(

Quinn Taylor
  • 44,553
  • 16
  • 113
  • 131
  • 1
    You also have a typo: forKey:, not forkey:. And for the record, `NSMutableDictionary` does support `setValue:forKey:`, but I still prefer to use `setObject:forKey:`. – Alex Jul 28 '09 at 18:10

2 Answers2

26

A) forkey: should be forKey:. Capitalization is important.

B) setValue:forKey: is a KVC method. It may work as you expect here, but the proper method to use for NSMutableDictionary is setObject:forKey:

kperryua
  • 10,524
  • 1
  • 38
  • 24
  • You'll also find, even after correcting the method name, that KVC keys must be strings. You have to use the native NSMutableDictionary `setObject:forKey:` method to use arbitrary objects as keys. – Chuck Jul 28 '09 at 18:24
6

You want setObject:forKey:. setValue:forKey: is part of the key-value coding protocol. NSMutableDictionary provides setObject:forKey:.

Alex
  • 26,829
  • 3
  • 55
  • 74