I'm learning programming in Objective-C and I can't understand what a static method is.
Objective-C doesn't have "static methods". It also doesn't have private methods. It does have class methods (marked with a +
) and instance methods (marked with a -
). Class methods are similar to static methods in C++ in that you can call them without having an instance of the class that defines them, so I expect you're asking about class methods and why they're useful.
In Objective-C, classes themselves are a kind of object, and you can send messages to them just as you send messages to an instance of a class (although the messages that you can send are different). Class methods are used whenever you want the class to do something but don't have an instance of the class. They're often used for getting or creating instances of the class. A perfect example is the +alloc
method. +alloc
creates an instance of a class by allocating memory for that instance; it's then up to you to initialize the instance with an appropriate initializer:
Foo *f = [[Foo alloc] initWithBar:bar];
Here we're sending the message alloc
to the object that is the Foo class itself in order to create an new instance of Foo. Then we're sending the message initWithBar:
to the new instance in order to initialize it with the object bar
.
Similarly, class methods are often used as "convenience constructors" to create an object in one step rather than the two above:
NSString *s = [NSString stringWithFormat:@"%f", someFloat];
Here we just send a message to the class NSString (remember, classes are themselves objects) and get back a properly initialized string.
Without class methods, there would be no way to create instances of classes.
Sometimes a class manages access to a shared instance of itself. In those cases, the class will often provides a method to retrieve that shared object:
NSFileManager *fileManager = [NSFileManager defaultManager];
Most of the time you don't need to create your own NSFileManager instance -- you can just use the shared object. Having the NSFileManager class manage that object makes sense -- it's easy to figure out how to get the shared instance, and the way the shared file manager is handled may change as the implementation of NSFileManager changes.
From what I read on Wikipedia, it sounds like a class method that
can't access anything in self.
self
is valid in a class method, but it refers to the class object and not to any instance of the class. So you're right that you can't access any instance variables from within a class method, but that doesn't mean that the message should be a "stand-alone function" entirely unrelated to the class.
self
. There is no technical need to associate it with a class, nevertheless it can make a lot of sense to keep it there (for example, to keep the complete source code of a class file, including static "helper methods", together in a logical unit).