Reputation: 8589
I am getting this error when trying to add the NSString object named object
to my array :
erminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x7fc48ae52ba0'
Not sure why this is so. I was originally using NSArray to changed it to NSMutableArray but I am still having problems with it. Code is below:
-(NSMutableArray *)getReplyArrayForMessage: (NSString *)message {
//get the array
NSMutableArray *replies = [self.messageDictionary objectForKey:message];
NSLog(@"%@",replies);
//if no replies we init the base set
if([replies count]==0) {
//get the base array
//this also works if a key just isn't in the dictonary
return replies=[self getBaseArray];
}
else {
//add the other message
NSString *object = @"Send a different message";
[replies addObject:object];
return replies;
}
}
If anyone could give me a pointer to why this is happening I would appreciate it. Noob here.
Upvotes: 1
Views: 290
Reputation: 122391
The array is immutable (NSArray
), not mutable (NSMutableArray
). You can create a mutable array from an immutable array using mutableCopy
:
NSMutableArray *replies = [[self.messageDictionary objectForKey:message] mutableCopy];
I know this from the exception text:
-[__NSArrayI addObject:]: unrecognized selector sent to instance ...
^^^^^^^^^^
EDIT I've missed off some important information from my original answer.
Having used mutableCopy
you now have a copy of the array and the original array (from self.messageDictionary objectForKey:message
) will remain unchanged after you add your element. This is almost certainly not what you intended.
As I've mentioned in the comments below, you probably want to create a custom object to hold these details (or an array of custom objects) that should be created from the message dictionary as soon as you receive it. The effort required to create a custom object will pay for itself tenfold in the long term.
Upvotes: 2
Reputation: 22731
You are trying to add an NSString
to an NSArray
(which looks like an NSMutableArray
) since you initialized it as one. This means that the object that you store in your messageDictionary
is actually of type NSArray
, and not NSMutabelArray
. So, assigning it to an object of type NSMutableArray
won't actually change its type and make it mutable.
It's an easy fix:
NSMutableArray *replies = [[NSMutableArray alloc] initWithArray:(NSArray *) [self.messageDictionary objectForKey:message]];
Or you can go with mutableCopy
(as suggested by @trojanfoe) which is a shortcut but will lead to the same result.
I can tell because the error message says -[__NSArrayI addObject:]: unrecognized selector sent to instance 0x7fc48ae52ba0'
. Notice the I
at the end of __NSArrayI
, this means that this array is actually immutable, so you can't add objects to it.
Upvotes: 1