Objective-C - difference between class method and static method?

 Static methods neither require an instance of the class nor can they implicitly access the data (or this, self, Me, etc.) of such an instance.

This describes exactly what Objective-C's class methods are not.

An Objective-C class method very much requires an instance that is the target of the method invocation. That is, it requires an instance of the metaclass that describes the class object being invoked.

 

Unlike static methods, Objective-C's class methods can be inherited (which, in combination with having the aforementioned self, is exactly why many classes can share a single, simple, implementation of+alloc on NSObject without needing their own custom implementations) and invoking a class method goes through the exact same objc_msgSend* based dispatch mechanism as any other method call site.

 

Objective-C's class methods can be overridden across the class hierarchy and they can be swizzled.

None of which is supported in languages that typically offer static methods in lieu of class methods.

 

The bottom line is that static methods and class methods are very different. While that difference is mostly transparent for day to day coding purposes, there are still situations where knowing how class methods work can save you a ton of unnecessary lines of code.

 

For example, you can't do this with static methods:

@interface AbstractClass:NSObject
+ factory;
@end

@implementation AbstractClass
+ factory
{
    return [[[self alloc] init] autorelease];
}
@end

@interface Concrete1:AbstractClass
@end
@implementation Concrete1
@end
@interface Concrete2:AbstractClass
@end
@implementation Concrete2
@end

void foo() {
    Concrete1 *c = [Concrete1 factory];
    Concrete2 *d = [Concrete2 factory];
    ... etc ...
}    

 

http://stackoverflow.com/questions/8089186/objective-c-difference-between-class-method-and-static-method

 

 

转载于:https://www.cnblogs.com/season2009/archive/2012/06/28/2567653.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值