我需要释放一个常量 NSString 吗?
我正在阅读内存管理规则,它说
- (void)printHello {
NSString *string;
string = [[NSString alloc] initWithString:@"Hello"];
NSLog(@"%@", string);
[string release];
}
您拥有所有权并且必须释放 string
,但我对 @"Hello"
很好奇。 @" "
是创建和 NSString
的语法,它是一个对象。那这样不会泄露吗?
I'm reading memory management rules to this point where it said
- (void)printHello {
NSString *string;
string = [[NSString alloc] initWithString:@"Hello"];
NSLog(@"%@", string);
[string release];
}
you have ownership and have to release string
, but I'm curious about the @"Hello"
. @" "
is the syntax for creating and NSString
, and it's an object. So doesn't that get leaked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@"…"
是NSString
的文字实例。当编译器看到文字字符串时,它会将字符串映射到二进制文件(例如您的程序),并且在加载二进制文件时(例如当您运行程序时)该字符串可作为NSString
对象使用。您不必管理文字字符串占用的内存,因为它们是二进制文件的固有部分 - 它们始终可用,永远不会被释放,并且您不必担心管理它们的内存。@"…"
is a literal instance ofNSString
. When the compiler sees a literal string, it maps the string into the binary file (e.g. your program) and the string is available as anNSString
object when the binary is loaded (e.g. when you run your program). You don’t have to manage the memory occupied by literal strings because they’re an intrinsic part of your binary — they are always available, they never get released, and you don’t have to worry about managing their memory.巴伐利亚的回答是正确的。出于好奇,我可以补充一点,这记录在 Apple 的“字符串编程指南”中,特别是“创建字符串” (强调我的):
Bavarious's answer is correct. For the curious, I can add that this is documented in Apple's “String Programming Guide”, specifically the section “Creating Strings” where it says (emphasis mine):