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 stringByAppendingString: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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With