classDiagram\
Class A <|-- Object a : 實例化\
Class A : +themeName: NSString*\
Class A : +logIn(UIBarButtonItem*)\
Class A : +logOut()\
Object a : themeName = "willingseal"\
Object a : logOut()
@interface A\ @property (nonatomic, strong) NSString *themeName; // 屬性:對象類型\ - (void)logIn:(UIBarButtonItem *)buttonItem; // 方法:帶參數\ - (void)logOut; // 方法:無參數\ @end
@property 自動生成存取方法(getter/setter)及實例變量 _themeName。nonatomic 非原子操作(多線程不安全但快),strong 強引用(ARC 環境下保持對象存活)。themeName 是 NSString 對象,而非基本類型。- 表示實例方法,+ 表示類方法。(void) 返回類型。logIn: 選擇器名稱,冒號後跟參數類型與名稱。A *a = [[A alloc] init]; // 分配內存並初始化\ a.themeName = @"willingseal"; // 點語法調用 setter\ [a logOut]; // 消息發送調用方法
alloc 分配原始內存,init 初始化實例變量。a.themeName = ... 編譯器轉為 [a setThemeName:...]。[a logOut] 為標準消息發送。| 術語 | 說明 | 代碼體現 |
|---|---|---|
| 類 | 對象的模板,定義屬性與方法 | @interface A |
| 對象 | 類的實例,佔用內存存儲屬性值 | A *a = [[A alloc] init] |
| 屬性 | 對象持有的數據,本質是實例變量+存取方法 | @property ... themeName |
| 方法 | 對象的行為,本質是函數指針+消息分發 | - (void)logOut |
| 實例化 | 從類創建對象的過程 | alloc/init |
@interface B : A,子類繼承父類屬性方法,可重寫/擴展。@protocol MyDelegate ... @end ,定義介面契約,類採用協議 @interface C 。@interface A (Extension) ... @end,無需子類即可為現有類添加方法。retain/release,strong/weak 控制所有權。理解「類是模板、對象是實例、屬性是數據、方法是行為」這一核心關係,是掌握 Objective-C 面向對象編程的基石。