字符串声明和赋值:3 种方法
对于非保留字符串声明,这三行是否相同?
NSString *list2 = self.map;
NSString *list2 = [NSString stringWithFormat:@"%@", self.map];
NSString *list2 = [NSString stringWithString:self.map];
他们都创建了一个自动释放的字符串对象,对吧?其中是否有首选方法,或者根据这些方法,“list2”的内存使用或行为是否有任何差异?
出于某种原因,我发现 Objective-C 中的字符串操作是其他语言中最令人困惑的过渡。
For non-retained string declarations, are these three lines the same?
NSString *list2 = self.map;
NSString *list2 = [NSString stringWithFormat:@"%@", self.map];
NSString *list2 = [NSString stringWithString:self.map];
They all create an autoreleased string object, right? Is there a preferred method among these, or are there any differences in the memory usage or behavior of "list2" depending on these methods?
For some reason, I find the manipulation of strings in objective-C the most confusing transition from other languages.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单的事实,在上述三种情况下您并不拥有该对象,
所以你可以使用,
这更多地与开发人员的选择有关,而不是与性能有关。
浏览内存管理编程指南
The simple fact, You don't own the object in the above three cases,
So you could use either,
This is more related to choice of developer then performance.
Go through the Memory Management Programming Guide
不,第一个只是将
string.map
返回的指针分配给list2
。第二个和第三个理论上会创建您不拥有的新NSString
并将它们分配给list2
。但是,如果 string.map 返回一个不可变的字符串,则第三个字符串可能会为您提供相同的指针(可能保留并自动释放)。在所有情况下,您都不拥有(新)字符串。这实际上就是您需要知道的全部内容。它们可能是自动释放的,但这与您使用它们无关。
No, the first one merely assigns the pointer returned by
string.map
tolist2
. The second and third ones theoretically create newNSStrings
that you don't own and assign them tolist2
. However, ifstring.map
returns an immutable string, the third one will probably give you the same pointer (possibly retained and autoreleased).In all cases you do not own the (new) string. That's actually all you need to know. They may be autoreleased, but it is not relevant to you using them.