Goal c add string object to array

I searched everywhere for this, on the Internet, on stack overflows and cannot still understand what I'm doing wrong.

I am trying to add an element to an existing NSMutableArray. But it crashes on line 4:

-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x897b320 

Code:

 NSMutableArray *mystr = [[NSMutableArray alloc] init]; mystr = [NSArray arrayWithObjects:@"hello",@"world",@"etc",nil]; NSString *obj = @"hiagain"; [mystr addObject:obj]; 

What am I doing wrong? It drives me crazy!!!

+4
source share
5 answers

Your array does not change !. Use NSMutableArray

 mystr = [NSMutableArray arrayWithObjects:@"hello",@"world",@"etc",nil]; 

You get an unrecognized selector because NSArray does not contain the addObject method

+9
source

Your code should be:

 NSMutableArray *mystr = [[NSMutableArray alloc] initWithObjects:@"hello",@"world",@"etc",nil]; NSString *obj = @"hiagain"; [mystr addObject:obj]; 
+3
source

Ahhhhh noticed this already

Line 2 should be:

 [NSMutableArray arrayWithObjects:@"hello",@"world",@"etc",nil]; 

Sorry to waste your time on this!

0
source

In the second line, you reassign an instance of NSArray instead of NSMutableArray for the mystr variable.

Try something like this:

 NSMutableArray *mystr = [NSMutableArray arrayWithObjects:@"hello",@"world",@"etc",nil]; [mystr addObject:@"hiagain"] 
0
source

Initially, you create mystr as a modified array, but then assign it to the standard NSArray in the next line. Instead of calling arrayWithObjects, add each element using addObjects or another function that does not create a new immutable array.

0
source

All Articles