Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C accessing / changing array elements in a multidimensional array (NSArray)

I'm trying to change a value in a multidimensional array but getting a compiler error:

warning: passing argument 2 of 'setValue:forKey:' makes pointer from integer without a cast

This is my content array:

NSArray *tableContent = [[NSArray alloc] initWithObjects:
                [[NSArray alloc] initWithObjects:@"a",@"b",@"c",nil],
                [[NSArray alloc] initWithObjects:@"d",@"e",@"f",nil],
                [[NSArray alloc] initWithObjects:@"g",@"h",@"i",nil],
                 nil];

This is how I'm trying to change the value:

[[tableContent objectAtIndex:0] setValue:@"new value" forKey:1];

Solution:

 [[tableContent objectAtIndex:0] setValue:@"new val" forKey:@"1"];

So the array key is a string type - kinda strange but good to know.

like image 830
dan Avatar asked Jan 18 '10 19:01

dan


2 Answers

NSMutableArray *tableContent = [[NSMutableArray alloc] initWithObjects:
                    [NSMutableArray arrayWithObjects:@"a",@"b",@"c",nil],
                    [NSMutableArray arrayWithObjects:@"d",@"e",@"f",nil],
                    [NSMutableArray arrayWithObjects:@"g",@"h",@"i",nil],
                     nil];

[[tableContent objectAtIndex:0] replaceObjectAtIndex:1 withObject:@"new object"];

You don't want to alloc+init for the sub-arrays because the retain count of the sub-arrays will be too high (+1 for the alloc, then +1 again as it is inserted into the outer array).

like image 113
dreamlax Avatar answered Oct 06 '22 00:10

dreamlax


You're creating immutable arrays, and trying to change the values stored in them. Use NSMutableArray instead.

like image 40
NSResponder Avatar answered Oct 06 '22 01:10

NSResponder