Reputation: 4129
I've looked everywhere for this, online, on stack overflow and cannot still work out what I'm doing wrong.
I'm trying to add an element to an existing NSMutableArray. But it crashes on line 4:
-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x897b320
The code:
NSMutableArray *mystr = [[NSMutableArray alloc] init];
mystr = [NSArray arrayWithObjects:@"hello",@"world",@"etc",nil];
NSString *obj = @"hiagain";
[mystr addObject:obj];
What am I doing wrong? This is driving me crazy!!!
Upvotes: 8
Views: 43555
Reputation: 4129
Ahhhhh spotted it already
Line 2 should be:
[NSMutableArray arrayWithObjects:@"hello",@"world",@"etc",nil];
Sorry to waste your time with that!
Upvotes: 0
Reputation: 1877
You originally create mystr as a mutable array, but then assign it to a standard NSArray in the next line. Instead of calling "arrayWithObjects," add each item using "addObjects" or some other function that doesn't create a new immutable array.
Upvotes: 0
Reputation: 49354
The second line you're reassigning an instance of NSArray
rather of NSMutableArray
to your mystr
variable.
Try something like this:
NSMutableArray *mystr = [NSMutableArray arrayWithObjects:@"hello",@"world",@"etc",nil];
[mystr addObject:@"hiagain"]
Upvotes: 0
Reputation: 318814
Your code should be:
NSMutableArray *mystr = [[NSMutableArray alloc] initWithObjects:@"hello",@"world",@"etc",nil];
NSString *obj = @"hiagain";
[mystr addObject:obj];
Upvotes: 3
Reputation: 13713
You array is not mutable!. Use NSMutableArray
mystr = [NSMutableArray arrayWithObjects:@"hello",@"world",@"etc",nil];
You get unrecognized selector since NSArray
does not contain the addObject method
Upvotes: 14