@“某些文本”是否是?返回一个自动释放或保留 1 的对象?
给定以下代码:
// Initialize string
NSString *name = @"Franzi";
@"" 宏创建一个带有给定文本(此处为名称 Franzi)的 NSString 和 RETAIN COUNT OF 1?
那么 @"" 给出一个 NSString 是否必须释放?我对这个物体负责吗? 第二个代码示例让我感到困惑,尽管我是这样使用它的:
NSSting *message;
message = [NSString stringWithFormat:@"Hello @%!",name];
//message = [NSString stringWithFormat:@"Hello Girl!"];
所以消息在下一个运行循环 k 中被释放。但是作为 stringWithFormat 参数给出的 NSString 是什么呢?
类对象 NSString 是否释放作为参数给出的 NSString @"Hello %@"/@"Hello Girl" ? 或者 @""-Konstruktor 只返回自动释放的 NSString?
Given this code:
// Initialize string
NSString *name = @"Franzi";
@"" macro creates a NSString with given text (here the name Franzi) and a RETAIN COUNT OF 1?
So @"" gives an NSString with have to be released or not? Am I responsible for this object?
Second code example then confuses me, even though I am using it that way:
NSSting *message;
message = [NSString stringWithFormat:@"Hello @%!",name];
//message = [NSString stringWithFormat:@"Hello Girl!"];
So message gets released in next run loop, k. But what is with the NSString given as argument for stringWithFormat?
Does the class object NSString release the NSString @"Hello %@"/@"Hello Girl" given as arguement?
Or does @""-Konstruktor only give back autoreleased NSStrings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NSString
文字表示法@""
为您提供编译时常量字符串,它们驻留在自己的内存空间中并具有常量地址。与流行的看法相反,不释放文字字符串的原因并不是因为它们是自动释放池的一部分。它们不是——相反,它们在编译时分配的同一内存空间中度过了整个应用程序的生命周期,并且永远不会在运行时释放。仅当应用程序进程终止时它们才会被删除。
也就是说,您唯一需要内存管理常量
NSString
的时候是您自己保留或复制它们时。在这种情况下,您应该释放保留或复制的指针,就像释放任何其他对象一样。另一件事:文字本身不需要内存管理。但是,如果您将它们作为参数传递给
NSString
的便捷方法或初始化程序,就像您使用stringWithFormat:
所做的那样,那么这些方法和初始化程序返回的对象将遵循所有方法和初始化程序内存管理规则正常。The
NSString
literal notation@""
gives you compile-time constant strings that reside in their own memory space and have constant addresses.Contrary to popular belief, the reason why you don't release literal strings is not because they are part of the autorelease pool. They aren't — instead, they spend the entire application's lifetime in that same memory space they're allocated at compile time, and never get deallocated at runtime. They're only removed when the app process dies.
That said, the only time you need to memory-manage constant
NSString
s is when you retain or copy them for yourself. In that case, you should release your retained or copied pointers, just like you do any other object.Another thing: it's the literals themselves that don't need memory management. But if you pass them as arguments to
NSString
's convenience methods or initializers, like you do withstringWithFormat:
, then it's those objects returned by the methods and initializers that follow all memory management rules normally.