Phil
Phil

Reputation: 3045

"unrecognized selector sent to instance" exception error

I've read all the "unrecognized selector sent to instance" answers, but they don't seem to apply to my situation.

I've setting up a NSMutableDictionary like this...

  NSMutableDictionary *ObjectDynamic = [NSDictionary dictionaryWithObjectsAndKeys:pObject, @"pFObject",tObject, @"tFObject",nil];

and then at some later point in the code I'm trying to add in another object/key, with this...

[ObjectDynamic setObject:mySprite forKey:@"pSObject"];

But I'm getting an exception on that line, with the...

-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance

Is it not possible to add in another key/value pair like that?

Edit

Simple mistake, I just was trying to make a NSDictionary rather than a NSMutableDictionary! Thanks for the answers anyway.

Upvotes: 1

Views: 4815

Answers (2)

DrummerB
DrummerB

Reputation: 40211

That's because you initialize an immutable NSDictionary that doesn't have a setObject:forKey: method. Initialize a mutable one instead:

NSMutableDictionary *ObjectDynamic = [NSMutableDictionary 
    dictionaryWithObjectsAndKeys:pObject, @"pFObject",tObject, @"tFObject",nil];

Since Xcode 4.4 you can also use the new dictionary literals to initialize immutable dictionaries very easily and then use mutableCopy.

NSMutableDictionary *objectDynamic = [@{@"pFObject" : pObject, 
                                        @"tFObject" : tObject} mutableCopy];

Note, that in Objective-C you should start variable names with lower case letters.

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

In order to be able to change the content of a dictionary, you need to make NSMutableDictionary, not an immutable NSDictionary:

NSMutableDictionary *ObjectDynamic = [NSMutableDictionary // <<== Here
    dictionaryWithObjectsAndKeys:pObject, @"pFObject",tObject, @"tFObject",nil
];

Upvotes: 1

Related Questions