: 如 @interface Child : Parent// 父類 @interface Triangle : NSObject @property double a, b, c; - (instancetype)initWithA:(double)a B:(double)b C:(double)c; - (double)area; @end // 子類:無任何代碼,自動獲得父類所有能力 @interface TriangleSub : Triangle @end @implementation TriangleSub @end // 使用 TriangleSub *sub = [[TriangleSub alloc] initWithA:10 B:11 C:12]; double area = [sub area]; // 直接調用父類方法
核心規則:方法調用根據對象實際內存類型(isa指針指向的類)決議,而非變量聲明類型。
@interface TestClass : NSObject
- (void)test;
@end
@interface SubA : TestClass @end
@implementation SubA
- (void)test { NSLog(@"SubA test"); }
@end
@interface SubB : TestClass @end
@implementation SubB
- (void)test { NSLog(@"SubB test"); }
@end
// 測試
SubA *a = [[SubB alloc] init]; // 聲明SubA*,實際指向SubB對象
[a test]; // 輸出:"SubB test" —— 運行時根據實際類型調用
id關鍵字:編譯期不指定類型,運行時同樣動態分發,但失去IDE代碼提示。
將其他對象作為自身部分(屬性),復用現成功能,而非繼承。
// SDK提供組件
@class Keyboard, Mouse, Monitor, CPU;
@interface Computer : NSObject
@property (strong, nonatomic) Keyboard *keyboard;
@property (strong, nonatomic) Mouse *mouse;
@property (strong, nonatomic) Monitor *monitor;
@property (strong, nonatomic) CPU *cpu;
@end
@implementation Computer
- (instancetype)init {
self = [super init];
if (self) {
self.keyboard = [[Keyboard alloc] init];
self.mouse = [[Mouse alloc] init];
self.monitor = [[Monitor alloc] init];
self.cpu = [[CPU alloc] init];
}
return self;
}
@end
| 類別 | 關鍵字 | 說明 |
|---|---|---|
| 讀寫權限 | readwrite | 默認,可讀可寫 |
| readonly | 只讀 | |
| 內存管理 | assign | 默認,基本類型/弱引用 |
| strong | 對象強引用(ARC下保留) | |
| weak | 弱引用,對象釋放自動置nil | |
| copy | 複製語義,常用NSString/Block | |
| 線程安全 | atomic | 默認,線程安全但較慢 |
| nonatomic | 非原子,高性能,常用 |
重寫父類方法時,super調用父類實現,避免完全覆蓋。
// 基礎組件
@interface AirConditioner : NSObject
- (void)cooling; // 制冷
@end
@interface FormaldehydeRemover : NSObject
- (void)removeFormaldehyde; // 除甲醛
@end
// 高級空調
@interface AdvancedAC : AirConditioner
@property (strong, nonatomic) FormaldehydeRemover *remover;
@end
@implementation AdvancedAC
- (instancetype)init {
self = [super init];
if (self) self.remover = [[FormaldehydeRemover alloc] init];
return self;
}
- (void)cooling {
[super cooling]; // 1. 執行父類制冷邏輯
[self.remover removeFormaldehyde]; // 2. 額外除甲醛
}
@end