5

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.

4 Answers 4

11
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).

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

You want either NSMutableArray's insertObject:atIndex: or replaceObjectAtIndex:withObject: (the former will push the existing element back if one already exists, while the latter will replace it but doesn't work for indices that aren't already occupied). The message setValue:forKey: takes a value type for its first argument and an NSString for its second. You're passing an integer rather than an NSString, which is never valid.

3 Comments

There is no message like setObject:atIndex: but setObject:forKey:. But still get the same error.
There is no setObject:atIndex: for NSMutableArray, instead there is replaceObjectAtIndex:withObject:. developer.apple.com/mac/library/documentation/Cocoa/Reference/…
Apologies, posted while running out the door and made up a method. I've corrected to explain the two methods that I was conflating in my head.
0

Sorry for responding 1 and half years old question :D
I got the same problem, and at last I solved it with counting the elements, then do addObject to push to the array element

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.