如何更改 NSMutableArray 内 NSString 的值?

发布于 2025-01-02 19:23:28 字数 440 浏览 1 评论 0原文

我有一个可变的字符串数组。对于此示例,假设其中有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

在巴黎塔顶看东京樱花 2025-01-09 19:23:29

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

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

交换数组中的字符串需要执行以下操作:

- (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
}

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:

- (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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文