Class method (original) (raw)
A class method is a method that operates on class objects rather than instances of the class. In Objective-C, a class method is denoted by a plus (+) sign at the beginning of the method declaration and implementation:
To send a message to a class, you put the name of the class as the receiver in the message expression:
Subclasses
You can send class messages to subclasses of the class that declared the method. For example, NSArray
declares the class method array
that returns a new instance of an array object. You can also use the method with NSMutableArray
, which is a subclass of NSArray
:
NSMutableArray *aMutableArray = [NSMutableArray array];
In this case, the new object is an instance of NSMutableArray
, not NSArray
.
Instance Variables
Class methods can’t refer directly to instance variables. For example, given the following class declaration:
@interface MyClass : NSObject { |
---|
NSString *title; |
} |
+ (void)classMethod; |
@end |
you cannot refer to title
within the implementation of classMethod
.
self
Within the body of a class method, self
refers to the class object itself. You might implement a factory method like this:
+ (id)myClass { |
---|
return [[[self alloc] init] autorelease]; |
} |
In this method, self
refers to the class to which the message was sent. If you created a subclass of MyClass
:
@interface MySubClass : MyClass { |
---|
} |
@end |
and then sent a myClass
message to the subclass:
id instance = [MySubClass myClass];
at runtime, within the body of the myClass
method, self
would refer to the MySubClass
class (and so the method would return an instance of the subclass).