类方法(class method)

转载请注明出处
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;
 
  
@end
you 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 {
 
  
}
 
  
@end
and 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值