理解数组指针
我是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,他们会的。但是如果您阅读uppercaseString 的文档,您会发现它不会就地修改字符串。相反,它返回原始字符串的新大写版本。
NSString
上的所有方法都是这样工作的。您需要一个 NSMutableString 实例才能就地修改其内容。但是 NSMutableString 没有相应的大写方法,因此您必须自己编写它(作为 NSMutableString 上的类别)。
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 onNSString
work like that.You would need an instance of
NSMutableString
to be able to modify its contents in place. ButNSMutableString
does not have a corresponding uppercase method, so you would have to write it yourself (as a category onNSMutableString
).当然!!数组中的任何字符串都不会像语句 [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...!!