转载请注明出处
http://blog.csdn.net/sdnxr/article/details/43155705
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:
类方法操作的是类对象而不是类的实例。在OC中,使用一个放置在方法声明和实现之前的“+”号来标记类方法:
+ (void)classMethod;
To send a message to a class, you put the name of the class as the receiver in the message expression:
向一个类传递消息,你需要将这个类作为方法的接收者:
[MyClass classMethod];
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
:
在子类中,你可以使用父类声明的方法。举个例子,NSArray类声明了类方法array,该方法返回一个新的数组实例对象。你可以在NSArray的子类NSMutableArray中使用该方法:
NSMutableArray *aMutableArray = [NSMutableArray array];In this case, the new object is an instance of
NSMutableArray
, not
NSArray
.
上例中,新生成的对象是NSMutableArray的实例,而不是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;
@endyou cannot refer to
title
within the implementation of
classMethod
.
在classMethod的实现中,你不可以引用title。
self(self指针)/*注意*/
Within the body of a class method,
self
refers to the class object itself. You might implement a factory method like this:
在类方法中,self指向类对象本身。你可以如下实现一个工厂方法:
+ (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
:
在这个方法中,self指向消息的接受类。如果你创建了如下MyClass的子类:
@interface MySubClass : MyClass {
}
@endand then sent a
myClass
message to the subclass:
然后向MySubClass发(diao)送(yong)了消(fang)息(fa)myClass:
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).
运行时,在myClass方法中,self指向MySubClass类(该方法返回一个MySubClass的实例)。
转载请注明出处
http://blog.csdn.net/sdnxr/article/details/43155705