objective-c - 如何更改 NSMutableArray 中 NSString 的值?

标签 objective-c ios nsstring nsmutablearray

我有一个可变的字符串数组。对于这个例子,假设其中有 2 个字符串。

我想做的操作是获取第一个字符串并将第二个字符串的值赋给它。

我正在尝试这样的事情:

- (void) someAction {
    NSMutableArray * array = [[NSMutableArray alloc] initWithObjects: string1, string2, nil];
    NSString * firstString = [array objectAtIndex:0];
    NSString * secondString = [array objectAtIndex:1];
    firstString = secondString;
}

但是这个方法好像不行。正如我记录这两个字符串后,它们在操作后不会改变。

请指教。

最佳答案

您不能像那样更改数组中的字符串。

数组包含指向字符串的指针,当您将一个字符串分配给另一个字符串时,您只是在交换指针,而不是更改数组指向的字符串对象。

交换数组中的字符串需要做的是:

- (void) someAction {
    NSMutableArray * array = [[NSMutableArray alloc] initWithObjects: string1, string2, nil];
    NSString * secondString = [array objectAtIndex:1];
    [array replaceObjectAtIndex:0 withObject:secondString]; //replace first string with second string in the array
}

关于objective-c - 如何更改 NSMutableArray 中 NSString 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9140554/

相关文章:

iphone - 来自 "stringWithFormat:"的意外结果

ios - iOS 中的 malloc 校验和逻辑是什么?

ios - 按距离对 UITableView 进行排序/排序

ios - 以编程方式获取 iOS 应用程序中的内存使用情况 Live/Dirty Bytes(不是 Resident/Real Bytes)

ios - 选择器中具有不同参数类型的 respondsToSelector

iphone - 为什么自动释放对于 iPhone 应用程序特别危险/昂贵?

ios - 在 UITableView 中更改 AVPlayer 的 playerItem

iphone - iphone NSString 的问题

objective-c - 异步相当于 NSString 的 -initWithContentsOfURL :usedEncoding:error:

objective-c - 将密码范围移出界限