Objective-C 访问/更改多维数组 (NSArray) 中的数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2088679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C accessing / changing array elements in a multidimensional array (NSArray)
提问by dan
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.
所以数组键是字符串类型 - 有点奇怪但很高兴知道。
回答by dreamlax
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+initfor 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).
你不想alloc+init为子数组,因为子数组的保留计数太高(+1 为alloc,然后在插入外部数组时再次 +1)。
回答by NSResponder
You're creating immutable arrays, and trying to change the values stored in them. Use NSMutableArray instead.
您正在创建不可变数组,并尝试更改存储在其中的值。使用 NSMutableArray 代替。
回答by Chuck
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.
您需要 NSMutableArrayinsertObject:atIndex:或replaceObjectAtIndex:withObject:(如果现有元素已经存在,前者会将现有元素推回,而后者将替换它但不适用于尚未被占用的索引)。该消息setValue:forKey:的第一个参数采用值类型,第二个参数采用 NSString。您正在传递一个整数而不是 NSString,它永远不会有效。
回答by arufian
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 addObjectto push to the array element
抱歉回答了 1 年半的问题:D
我遇到了同样的问题,最后我通过计算元素来解决它,然后执行addObject推送到数组元素

