如何更改 NSMutableArray 内 NSString 的值?
我有一个可变的字符串数组。对于此示例,假设其中有 2 个字符串。
我想做的操作是获取第一个字符串并将第二个字符串的值分配给它。
我正在尝试这样的事情:
- (void) someAction {
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects: string1, string2, nil];
NSString * firstString = [array objectAtIndex:0];
NSString * secondString = [array objectAtIndex:1];
firstString = secondString;
}
但这个方法似乎不起作用。当我记录这两个字符串后,它们在操作后不会改变。
请指教。
I have a mutable array of strings. For this example, let's say there are 2 strings in it.
The operation that I would like to do is take the first string and assign the value of the second string to it.
I was trying something like this:
- (void) someAction {
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects: string1, string2, nil];
NSString * firstString = [array objectAtIndex:0];
NSString * secondString = [array objectAtIndex:1];
firstString = secondString;
}
But this method doesn't seem to work. As after I log these two strings, they don't change after the operation.
Please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能像这样更改数组中的字符串。
该数组包含指向字符串的指针,当您将一个字符串分配给另一个字符串时,您只是交换指针,而不是更改数组指向的字符串对象。
交换数组中的字符串需要执行以下操作:
You can't change strings in an array like that.
The array contains pointers to the strings, and when you assign one string to another you are just swapping pointers around, not changing the string object that the array points to.
What you need to do to swap the string in the array is this: