如何@“字符串”分配在内存中? [英] How are @"Strings" allocated in memory?

查看:137
本文介绍了如何@“字符串”分配在内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为以下代码分配内存。

I am curious of the memory allocation for the following code.

NSString *myString = [NSString string];



我知道这将创建一个自动释放的空字符串 @

I know this will create an autoreleased empty string, @""

当我随后调用

myString = @"Hello world";

我的引用与自动释放的对象相同 NSString 提供或者我只是分配一个我负责释放的新对象?

Is my reference the same as the autoreleased object NSString provided or did I just allocate a new object that I am responsible for releasing?

推荐答案

,问自己:

我用来创建此对象的方法...

Does the method I used to create this object...


  • new ?开头 new

  • li>
  • 包含 copy

  • 等于保留

  • begin with new?
  • begin with alloc?
  • contain copy?
  • equal retain?

如果您可以对任何一个回答是,那么您负责调用 autorelease 。 (请注意,Core Foundation对象的规则略有不同

If you can answer "Yes" to any of those, then you are responsible for invoking release or autorelease on the returned object. (Note that the rules for Core Foundation objects are slightly different. Also note that anything that the documentation explicitly says that contradicts this wins. The documentation always supersedes the guidelines)

在你的字符串的情况下,所有你的问题的答案是否,所以你不负责的对象。常量字符串(风格 @foo)硬编码到应用程序二进制文件中,并且无法解除分配。然而,这是一个实现细节。只要你遵循内存管理规则,你就会很好!

In the case of your string, the answers to all your questions are "no", so you are not responsible for the object. Constant strings (of the style @"foo") are hard-coded into the application binary and cannot be deallocated. That, however, is an implementation detail. As long as you follow the memory management rules, you'll be good!

这篇关于如何@“字符串”分配在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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