开发者

Objective-c class methods and copying return values

开发者 https://www.devze.com 2023-03-26 09:35 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号