是否@“一些文本"返回一个自动释放或保留 1 个对象? [英] Does @"some text" give an autoreleased or retain 1 object back?

查看:16
本文介绍了是否@“一些文本"返回一个自动释放或保留 1 个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此代码:

// Initialize string
NSString *name = @"Franzi";

@"" 宏使用给定的文本(这里是名称 Franzi)和 RETAIN COUNT OF 1 创建一个 NSString?

@"" macro creates a NSString with given text (here the name Franzi) and a RETAIN COUNT OF 1?

所以@"" 给出了一个必须被释放的 NSString 吗?我对这个对象负责吗?第二个代码示例让我感到困惑,即使我是这样使用的:

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!"];

所以消息在下一个运行循环中被释放,k.但是作为 stringWithFormat 参数给出的 NSString 是什么?

So message gets released in next run loop, k. But what is with the NSString given as argument for stringWithFormat?

类对象 NSString 是否释放了作为论证给出的 NSString @"Hello %@"/@"Hello Girl"?还是@""-Konstruktor 只返回自动释放的 NSStrings?

推荐答案

NSString 文字符号 @"" 为您提供驻留在它们自己的编译时常量字符串内存空间并具有恒定地址.

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.

也就是说,您唯一需要对 NSString 常量进行内存管理的时候是您自己保留或复制它们时.在这种情况下,您应该释放保留或复制的指针,就像处理任何其他对象一样.

That said, the only time you need to memory-manage constant NSStrings 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.

另一件事:不需要内存管理的是文字本身.但是,如果您将它们作为参数传递给 NSString 的便利方法或初始化程序,就像您对 stringWithFormat: 所做的那样,那么这些对象是由方法和初始化程序返回的所有对象内存管理规则正常.

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 with stringWithFormat:, then it's those objects returned by the methods and initializers that follow all memory management rules normally.

这篇关于是否@“一些文本"返回一个自动释放或保留 1 个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆