replaceObjectAtIndex似乎不起作用

Liv*_*oy7 2 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);
Run Code Online (Sandbox Code Playgroud)

从理论上讲,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
Run Code Online (Sandbox Code Playgroud)

请指教

谢谢

Mik*_*ler 5

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

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

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

NSLog(@"New object at index 1 AFTER is %@", newElement);
Run Code Online (Sandbox Code Playgroud)

在您获取原始字符串的那一刻,替换该数组的对象,然后再次打印出原始字符串.