Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[__NSArrayI replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance

I have a NSMutableArray, which I need to chance its values, but I have this error:
[__NSArrayI replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance 0x5291db0
This is the declaration of my NSMutableArray:

NSMutableArray *selectedOptions = [NSArray arrayWithObjects:[NSNumber numberWithInteger:0], nil]; 

Then, I'm using replaceObjectAtIndex method, of this way:

[self.selectedOptions replaceObjectAtIndex:0 withObject:[NSNumber numberWithInteger:1]];

But I get, that error, and I'm using NSMutableArray.
Thanks

like image 594
user1600801 Avatar asked Dec 07 '22 10:12

user1600801


2 Answers

You are creating a regular non-mutable NSArray. Your code should be

NSMutableArray *selectedOptions = [NSMutableArray arrayWithObjects:[NSNumber numberWithInteger:0], nil]; 

Objective C is very dynamic, so it does not catch this mistake at compile time.

like image 161
Sergey Kalinichenko Avatar answered May 19 '23 13:05

Sergey Kalinichenko


You need to initialize your NSMutableArray by doing

NSMutableArray *selectedOptions = [NSMutableArray alloc] init];

By initializing it with NSArray, you can no longer use the repalceObjectAtIndex:withObject: method and that's the cause of your problem.

After initializing your NSMutableArray with the line above, simply add objects to it with the addObject method.

like image 43
Rohan Agarwal Avatar answered May 19 '23 13:05

Rohan Agarwal