標籤:style blog color io 2014 ar cti div
最近溫習《learn objective-c on the mac》
第4章關於重寫的調用了[super setFillColor:c]很不理解其作用,可能是因為翻譯邏輯不清的原因吧,特地寫了個小例子理解一下
定義一個father類和son類
father:
#import <Foundation/Foundation.h>@interface father : NSObject{ int num;}-(void)setNum:(int)num;@end
#import "father.h"@implementation father-(void)setNum:(int)c{ num = c; NSLog(@"i am father");}@end
son:
#import <Foundation/Foundation.h>#import "father.h"@interface son : father-(void)setNum:(int)num;@end
#import "son.h"@implementation son-(void)setNum:(int)c{ num = c; if (1 == num) { NSLog(@"i am son"); } [super setNum:c];//這裡是關鍵 }@end
main:
#import <Foundation/Foundation.h>#import "son.h"int main(int argc, const char * argv[]){ @autoreleasepool { son *ii = [[son alloc]init]; [ii setNum:1]; } return 0;}
輸出結果:
2014-08-06 11:00:35.731 testtest[13606:303] i am son2014-08-06 11:00:35.732 testtest[13606:303] i am father
如果去掉[super setNum:c],就只輸出i am son。很明顯了,子類重寫方法添加自己的特性,而通過[super method]來保留父類的特性。