Objective-C如何处理不可变字符串的内存 [英] How Objective-C handles the memory of immutable strings
问题描述
在我的研究中,我遇到了一些奇怪的事情.
In my research I've come across something peculiar.
@interface Class {
NSString *_string
}
- (void) Method1 {
_string = @"ASDF";
}
最初,我认为_string
是自动释放池的一部分,实际上并没有考虑它的内存方面.
Intially I thought that _string
was part of the autorelease pools and really didn't think about the memory aspect of it.
在阅读此SO帖子后客观C NSString *属性保留计数奇数一个>
我已经意识到不可以,_string
的保留计数实际上是UINT_MAX
After reading this SO post Objective C NSString* property retain count oddity
I've realized that no, this is not the case, and that the retain count of _string
is actually UINT_MAX
很显然,我认为_string
是自动释放池的一部分,这是fl幸,而且我以某种方式解决了如何处理变量的问题.但是,我想知道的是:@"ASDF"
什么时候被扔掉的?我知道我应该使用属性和设置器,但是可能有很多代码看起来像这样,因为将常量分配给变量非常直观.
Obviously my thinking that _string
was part of the autorelease pool was a fluke, and how I handled the variable just somehow worked out. What I would like to know, though, is: when does @"ASDF"
get thrown away? I know I should be using properties and setters, but there is probably a lot of code out there that looks like this since assigning a constant to a variable is so intuitive.
这些不可变的文字NSString
的生命周期是什么?由于@"ASDF"
不再驻留在内存中,[_string length]
何时会真正返回错误?
What is the lifecycle of these immutable, literal NSString
s, and when will [_string length]
actually return an error since @"ASDF"
doesn't reside in memory anymore?
推荐答案
由编译器分配的字符串(格式为"STRING")是常量,并且 因此-retain,-release和-autorelease消息将被忽略. 在这种情况下,您不必释放或自动释放foo(但是 不会受伤).
Compiler allocated strings (of the format @"STRING") are constant, and so -retain, -release, and -autorelease messages to them are ignored. You don't have to release or autorelease foo in this case (but it won't hurt).
当你这样做的时候,在幕后
Under the hood when you do
NSString* yourString = @"ABC";
该字符串将存储在称为数据段的内存区域中.启动应用程序后,该区域永远不会改变.在这里,字符串被视为应用程序的常量.同时,字符串是一个对象,因此,如果要保留它,请调用retain
或copy
.
the string will be stored in a area of memory called data segment. This area never changes after the application is launched. Here strings are treated as constants for your app. At the same time a string is an object, so if you want to keep it you call retain
or copy
.
在竞争时
NSString* yourString = // alloc-init
您在堆上创建一个对象.如果忘记释放,则有内存泄漏.如果其他人破坏了它,并且您尝试访问它,则可能无法访问该内存位置.
you create an object on the heap. If you forget to release you have a memory leak. If someone else destroy it, and you try to access it, you have a bad access to that memory location.
希望有帮助.
这篇关于Objective-C如何处理不可变字符串的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!