【问题标题】:Objective-C accessing / changing array elements in a multidimensional array (NSArray)Objective-C 访问/更改多维数组 (NSArray) 中的数组元素
【发布时间】:2010-01-18 19:34:14
【问题描述】:

我正在尝试更改多维数组中的值,但出现编译器错误:

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

所以数组键是一个字符串类型 - 有点奇怪但很高兴知道。

【问题讨论】:

    标签: objective-c arrays multidimensional-array


    【解决方案1】:
    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。

      【讨论】:

        【解决方案3】:

        您需要 NSMutableArray 的 insertObject:atIndex:replaceObjectAtIndex:withObject:(如果现有元素已经存在,前者会将现有元素推回,而后者将替换它,但不适用于尚未被占用的索引)。消息setValue:forKey: 的第一个参数采用值类型,第二个参数采用 NSString。你传递的是一个整数而不是一个 NSString,它永远不会有效。

        【讨论】:

        • 没有像 setObject:atIndex: 这样的消息,而是 setObject:forKey:。但仍然得到同样的错误。
        • NSMutableArray 没有 setObject:atIndex:,而是有 replaceObjectAtIndex:withObject:developer.apple.com/mac/library/documentation/Cocoa/Reference/…
        • 道歉,跑出门的时候发帖,编了个办法。我已更正以解释我在脑海中混淆的两种方法。
        【解决方案4】:

        很抱歉回答 1 岁半的问题:D
        我遇到了同样的问题,最后我通过计算元素解决了它,然后addObject推送到数组元素

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-11
          • 2015-07-05
          • 2020-04-08
          • 2019-01-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多