NSObject(或 NSProxy)。@public/@protected 修飾)與公開方法(在 .h 中宣告者)。// 完全重寫:子類別自行實現,不呼叫 super
- (void)customMethod {
// 子類別專屬邏輯
}
// 部分重寫:擴充父類別行為,透過 super 呼叫父類別實現
- (void)customMethod {
[super customMethod]; // 先執行父類別邏輯
// 再執行子類別額外邏輯
}
重寫時不需在 .h 重新宣告;若父類別方法為私有(未在 .h 宣告),子類別同名方法視為新方法而非重寫。
類別的主要初始化入口,通常命名為 initWith…,責任鏈:
- (instancetype)initWithColor:(NSString *)color price:(NSString *)price {
if (self = [super init]) { // 必須呼叫 super 指定初始化器
_color = color;
_price = price;
}
return self;
}
instancetype 而非 id,編譯器可做型別檢查。類別方法,封裝 alloc + init,回傳自動釋放(ARC 下為強參考)物件:
+ (instancetype)appleWithColor:(NSString *)color price:(NSString *)price {
return [[self alloc] initWithColor:color price:price];
}
+ classNameWith… 或 + typeWith…。[[self alloc] init…] 而非硬編碼類別名,支援子類別繼承時正確建立子類別實例。autorelease。OC 物件本質是指標,賦值僅複製指標位址:
MyClass *obj1 = [[MyClass alloc] init]; MyClass *obj2 = obj1; // 兩指標指向同一記憶體 [obj1 release]; // 非 ARC 下釋放導致 obj2 成野指標
這也是引用計數機制存在的根本原因(詳見下一篇《Objective-C 記憶體管理》)。
[super designatedInitializer]。instancetype,內部使用 self 呼叫 alloc。