理解数组指针

发布于 2024-12-05 06:23:25 字数 337 浏览 2 评论 0原文

我是 Objective-C 的新手,需要有关指针概念的帮助。我已经编写了这段代码:

//myArray is of type NSMutableArray
NSString *objectFromArray = [myArray objectAtIndex:2];
[objectFromArray uppercaseString];

我假设这会更改 myArray[2] 处的字符串,因为我得到了指向它的实际指针。对取消引用的指针的任何更改是否都意味着该位置中的对象发生更改?或者这与“字符串不变性”有关?不管怎样,当我使用 NSLog 并迭代 myArray 时,所有字符串仍然是小写。

I'm new to Objective-C and need help with the concept of pointers. I've written this code:

//myArray is of type NSMutableArray
NSString *objectFromArray = [myArray objectAtIndex:2];
[objectFromArray uppercaseString];

I assumed that this would change the string at myArray[2] since I got the actual pointer to it. Shouldn't any changes to the dereferenced pointer mean that the object in that location changes? Or does this have something to do with 'string immutability'? Either way, when I use NSLog and iterate through myArray, all the strings are still lowercase.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

烟织青萝梦 2024-12-12 06:23:25

取消引用指针的任何更改是否都意味着该位置的对象发生更改?

是的,他们会的。但是如果您阅读uppercaseString 的文档,您会发现它不会就地修改字符串。相反,它返回原始字符串的新大写版本。 NSString 上的所有方法都是这样工作的。

您需要一个 NSMutableString 实例才能就地修改其内容。但是 NSMutableString 没有相应的大写方法,因此您必须自己编写它(作为 NSMutableString 上的类别)。

Shouldn't any changes to the dereferenced pointer mean that the object in that location changes?

Yes, they would. But if you read the documentation for uppercaseString, you see that it does not modify the string in place. Rather, it returns a new uppercase version of the original string. All methods on NSString work like that.

You would need an instance of NSMutableString to be able to modify its contents in place. But NSMutableString does not have a corresponding uppercase method, so you would have to write it yourself (as a category on NSMutableString).

不交电费瞎发啥光 2024-12-12 06:23:25

当然!!数组中的任何字符串都不会像语句 [objectFromArray uppercaseString] 一样转换为大写;会返回大写字符串,但该字符串未在任何对象中收集。 “uppercaseString”不会修改被调用的字符串对象本身......!!

of course!! no string in the array will be converted to uppercase as the statement [objectFromArray uppercaseString]; would have returned the uppercase string which was not collected in any object though. "uppercaseString" does not modify the string object itself with which is is called...!!

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