Objective-c class methods and copying return values
I'd like some help understanding the code snippet below. Specifically I'd like to know why the copy
keyword is used when methodB
calls methodA
.
+ (NSString*) methodA {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory,
NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
+ (NSString*) methodB:(NSString*)stringToAppend {
static NSString *s = nil;
if(!s) s = [[self methodA] copy];
return [s stringByAppending开发者_运维知识库String:stringToAppend];
}
Side note: Apparently class methods can call other class methods using self
(while instance methods must call class methods like this [ClassName classMethodName];
MethodB calls copy in case the NSString returned from methodA is actually a NSMutableString.
The copy is just there for security; you can feel safe knowing that nothing is changing the contents of that string while you're using it.
It's a common technique for dealing with objects that might be mutable when you don't want them to be.
What is paths[0]
? Assuming you meant [paths objectAtIndex: 0]
, you should at least autorelease it. You can then still copy it in methodB:
.
The string you return in methodB:
is already autoreleased, so that is fine.
精彩评论