Objective-C访问/更改多维数组(NSArray)中的数组元素

5

我正试图修改一个多维数组中的值,但是却得到了编译错误:

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

这是我的内容数组:
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];

这是我尝试更改值的方法:

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

解决方案:

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

因此,数组键是字符串类型 - 这有点奇怪,但需要知道。

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"];

不要对子阵列进行alloc+init,因为子阵列的保留计数会太高(alloc会增加1次,然后再次增加1次,因为它将插入到外部数组中)。


2
您正在创建不可变数组,并尝试更改其中存储的值。请改用NSMutableArray。

1
你需要使用NSMutableArray的insertObject:atIndex:或者replaceObjectAtIndex:withObject:方法(前者会将已有元素向后移动,而后者则会替换它,但是对于未被占用的索引无效)。setValue:forKey:方法的第一个参数是值类型,第二个参数是NSString类型。你传递了一个整数而不是NSString类型,这是无效的。

没有像setObject:atIndex:这样的消息,但是有setObject:forKey:。但仍然会得到相同的错误。 - dan
NSMutableArray 没有 setObject:atIndex: 方法,而是使用 replaceObjectAtIndex:withObject: 方法。请参考 http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html。 - dreamlax
抱歉,我在匆忙中发布了一种方法。我已经更正了,解释了我在脑海中混淆的两种方法。 - Chuck

0

非常抱歉回复了一个一年半前的问题 :D
我遇到了同样的问题,最后通过计算元素数量,然后使用addObject将其推入数组元素中解决了它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接