Is a literal NSString autoreleased or does it need to be released?

我的梦境 提交于 2019-11-27 12:19:40

问题


When creating a string using the following notation:

NSString *foo = @"Bar";

Does one need to release foo? Or is foo autoreleased in this case?


回答1:


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).




回答2:


As mentioned in the docs

http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Tasks/MemoryManagementRules.html

You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it.

Since you're not using alloc, copy, etc. you don't need to worry about releasing the object.




回答3:


I agree with @Ben\ Gottlieb at "Compiler allocated strings (of the format @"STRING") are constants" but as you have not initialized them via passing an alloc or retain message, you must not pass release or autorelease message to them otherwise your app will crash with the following log

"pointer being freed was not allocated"

NOTE

NSString *str = [NSString string];

is equivalent to:

NSString *str = [[[NSString alloc] init] autorelease];

so release or autorelease must not be passed here too.



来源:https://stackoverflow.com/questions/329977/is-a-literal-nsstring-autoreleased-or-does-it-need-to-be-released

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!