Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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];

like image 891
SundayMonday Avatar asked Aug 04 '26 03:08

SundayMonday


1 Answers

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.

like image 178
Terry Wilcox Avatar answered Aug 06 '26 22:08

Terry Wilcox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!