这篇文字讲解的是两个不相关的东东。
objc 的 class object 有点特别,对于 static data member 不太好实现,就不介绍了。
在 instance method 中调用 class method,记得写 [self class] 保证类继承时,正确调用到子类的 class method。
---------------- Father.h -----------------
#import <Foundation/Foundation.h>
@interface Father : NSObject {
}
+ (void) classMethod;
- (void) instanceMethod;
@end
#import "Father.h"
@implementation Father
+ (void) classMethod
{
NSLog(@"Father's classMethod!");
}
- (void) instanceMethod
{
NSLog(@"Father's instanceMethod!");
[[self class] classMethod];
}
@end
---------------- Son.h -----------------
#import "Father.h" @interface Son : Father { } + (void) classMethod; @end
---------------- Son.m -----------------
#import "Son.h"
@implementation Son
+ (void) classMethod
{
NSLog(@"Son's classMethod!");
}
@end
---------------- Main.m -----------------
#import "Son.h" int main() { Father *f = [[Father alloc] init]; Son *s = [[Son alloc] init]; [f instanceMethod]; [s instanceMethod]; [s release]; [f release]; return 0; }
评论