I would like to add a static NSString to an Objective-C class, however I am wary of managing its memory.
NSString *myImportantString = 0;
@implementation MySingletonClass
/* Option 1 */
+ (void)initialize {
myImportantString = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"criticalFolder"];
}
/* Option 2 */
+ (void)initialize {
NSString *tmp = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"criticalFolder"];
myImportantString = [[NSString alloc] initWithString:tmp];
}
In Option 1, myImportantString is an autoreleased object, so how do I know where/when it will be released? This uncertainty prompted me to instead use Option 2. However, as I am using ARC, How/when (if ever?) will it be released? According to the +initialize method, myImportantString is not used again in the method, and thus wouldn’t ARC insert the appropriate release code at the end of the +initialize method?
I am (relatively) confident that it will be handled correctly for me, but I would still like to know how it works.
Option 1 is fine because the global variable
myImportantStringdefaults tostrong. The string will never be released (which is fine for a global).