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

允我心安 提交于 2019-11-28 19:26:24

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

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.

Madhup Singh Yadav

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.

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