replaceObjectAtIndex似乎不起作用

时间:2012-05-30 15:24:38

标签: objective-c nsarray

在这里使用基本目标c示例,尝试将replaceObjectAtIndex用于数组,但它似乎没有工作。

我的代码:

 NSMutableArray *myArray=[NSMutableArray array];
    [myArray addObject:@"First string"];
    [myArray addObject:@"Second string"];
    [myArray addObject:@"Third string"];

    NSString *newElement=[myArray objectAtIndex:1];
    NSLog(@"New object at index 1 BEFORE is %@", newElement);
    [myArray replaceObjectAtIndex:1 withObject:@"Hello"];
    NSLog(@"New object at index 1 AFTER is %@", newElement);

理论上,newElement的输出现在应该显示“Hello”,但它仍然显示“Second String”

输出:

2012-05-30 11:21:16.638 cocoa lab[753:403] New object at index 1 BEFORE is Second string
2012-05-30 11:21:16.641 cocoa lab[753:403] New object at index 1 AFTER is Second string

请告知

谢谢

2 个答案:

答案 0 :(得分:5)

更换后需要从数组中获取新值

// ...
[myArray replaceObjectAtIndex:1 withObject:@"Hello"];

/* ADD THIS */
newElement=[myArray objectAtIndex:1];

NSLog(@"New object at index 1 AFTER is %@", newElement);

当你获取原始字符串时,替换数组的对象,然后再次打印出原始字符串。

答案 1 :(得分:0)

您需要在调用newElement后重置replaceObjectAtIndex:的值,因此在第二次记录该值之前添加另一行:

newElement=[myArray objectAtIndex:1];

更新1

并且不要感到难过 - 我们都曾经为自己做过这样或那样的事。 : - )

更新2

顺便说一下,一般来说避免这类问题的一个好方法是养成在这种情况下使用单独的局部变量的习惯,例如,你可以重写你发布的代码,如下所示:

NSString *initialValue = [myArray objectAtIndex:1];
NSLog(@"New object at index 1 BEFORE is %@", initialValue);

[myArray replaceObjectAtIndex:1 withObject:@"Hello"];

NSString *newValue = [myArray objectAtIndex:1];
NSLog(@"New object at index 1 AFTER is %@", newValue);