Search code examples
iphoneobjective-ciosnsmutabledictionary

iOS, NSMutableDictionary


I had a problem in my project where I declared in the header file an NSMutableDictionary property like so:

@property (copy, nonatomic) NSMutableDictionary *DataDict ;

Now in the implementation file, I go ahead and initialise this dictionary because I am gonna use it, like so:

DataDict = [[NSMutableDictionary alloc]init];

Now when I did this, the minute I try to add something to this dictionary I would get this error message:

-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0x885ae60 2012-10-19 16:51:56.040 testing[2297:c07] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0x885ae60'

After a while and running through my project a thousand times, I decided to uncomment my initialization line, like so

 //DataDict = [[NSMutableDictionary alloc]init];

and that fixed the problem.

My question is: Why?


Solution

  • The problem is in the way you have defined your property. If you change it to:

    @property (strong, nonatomic) NSMutableDictionary *DataDict ;
    

    instead of copy everything should be fine.

    This happens because you basically say that you want a copy of your object through your generated accessors, which returns an NSDictionary instead (an immutable copy).

    You can find more on objective-c properties here.

    Just as a sidenote: objective-c ivars usually start with a lowercase letter (uppercase names are used for classes), so dataDict should be preferred over DataDict.