简体   繁体   中英

objective-c static/class method definition - what is the difference between “static” and “+”?

I'm wondering if someone can explain the difference between the functions below. They are both static, but require different signature syntaxes. I'm wondering how these are handled at runtime, and why you would use one over the other?

+ (int) returnInt:(NSString *)myString1 withString2:(NSString *)myString2
{
    if ([myString1 isEqualToString:myString2])
        return 1;
    else 
        return 0;
}

vs.

static int returnInt(NSString *myString1, NSString *myString2)
{
    if ([myString1 isEqualToString:myString2])
        return 1;
    else 
        return 0;
}

Thanks!

Unlike in (say) C++, where static member functions are just ordinary functions in the class' namespace, Objective-C has proper class methods.

Since classes are objects, calling a class method is really like calling an instance method on the class. The main consequences of this are:

1) Calling a class method incurs a slight (although generally inconsequential) overhead, since method calls are resolved at runtime.

2) Class methods have an implicit 'self' argument, just like instance methods. In their case, 'self' is a pointer to the class object.

3) Class methods are inherited by subclasses.

together, 2 and 3 mean that you can do stuff like this with a class method:

+ (id) instance
{
    return [[[self alloc] init] autorelease];
}

then create a new class that inherits the method and returns a new instance of itself, rather than the superclass.

I believe that marking an ordinary c function static will just make it unavailable to files other than the one it's defined in. You'd generally do this if you wanted to make a helper function that is only relevant to one class and you wanted to avoid polluting the global namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM