Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you change the elements within an NSArray?

I am a bit confused as to how arrays are handled in Objective-C. If I have an array such as

NSarray *myArray = [[NSArray alloc]
                                  initWithObjects:@"N", @"N", @"N", @"N", @"N",
                                  nil];

how do I change the first occurrence to "Y"?

like image 232
Namhcir Avatar asked Dec 02 '22 01:12

Namhcir


2 Answers

You need an NSMutableArray ..

NSMutableArray *myArray = [[NSMutableArray alloc]
                                  initWithObjects:@"N", @"N", @"N", @"N", @"N",
                                  nil];

and then

[myArray replaceObjectAtIndex:0 withObject:@"Y"];
like image 149
Kal Avatar answered Dec 18 '22 02:12

Kal


You can't, because NSArray is immutable. But if you use NSMutableArray instead, then you can. See replaceObjectAtIndex:withObject::

[myArray replaceObjectAtIndex:0 withObject:@"Y"]
like image 41
Adam Batkin Avatar answered Dec 18 '22 01:12

Adam Batkin