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

查看:79
本文介绍了@“某些文字"是否在给一个自动释放或保留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?

Does the class object NSString release the NSString @"Hello %@"/@"Hello Girl" given as arguement? Or does @""-Konstruktor only give back autoreleased 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.

另一件事:不需要存储器管理的是文字本身.但是,如果像使用stringWithFormat:一样将它们作为NSString的便捷方法或初始化程序的参数传递,则这些方法和初始化程序返回的对象通常会遵循所有内存管理规则.

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天全站免登陆