面向設計師與初學者的 iOS 開發基礎教程。本文以建立簡單聯絡人介面為例,詳細講解類別結構、屬性與方法聲明、IBOutlet/IBAction 連接機制、@synthesize 自動生成存取器、手動記憶體管理 (MRC 時代) 的 retain/release 原理,奠定 Objective-C 物件模型認知基石。
#import // 引入 UIKit 框架所有公開介面
// 宣告 ContactViewController 為 UIViewController 子類別
@interface ContactViewController : UIViewController
// 屬性與方法聲明區 (在 @interface 與 @end 之間)
@property (nonatomic, retain) IBOutlet UIButton *websiteButton; // 屬性聲明
- (IBAction)openWebsite:(id)sender; // 方法聲明
@end
| 關鍵字 | 含義 |
|---|---|
@property | 聲明物件屬性,編譯器自動生成存取器宣告 (getter/setter) |
(nonatomic, retain) | nonatomic:非原子操作,多執行緒不加鎖,效能高 (絕大多數屬性用此);retain:設定時保留新值、釋放舊值 (MRC 記憶體語義) |
IBOutlet | 標記此屬性可在 Interface Builder 中連接視圖物件 |
UIButton *websiteButton | 類型為 UIButton 指針,名稱為 websiteButton |
- (IBAction)openWebsite:(id)sender | 實例方法,返回 void (IBAction 等同 void),參數 sender 為觸發事件的物件 |
| 命名慣例 | 類別名大寫開頭 (PascalCase);屬性/方法/變數小寫開頭 |
ContactViewController.xib.h 檔 @interface 區域websiteButton → ConnectopenWebsite → Connect@property 與 - (IBAction)... 代碼
#import "ContactViewController.h"
@implementation ContactViewController
// 告訴編譯器自動生成 websiteButton 的 getter/setter 實作
@synthesize websiteButton;
// ... 系統生成的模板代碼 ...
// 釋放資源 (MRC 時代必須)
- (void)dealloc {
[websiteButton release];
[super dealloc];
}
// 實作 IBAction 方法
- (IBAction)openWebsite:(id)sender {
// 打開網址邏輯
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://example.com"]];
}
@end
- (UIButton *)websiteButton (getter) 與 - (void)setWebsiteButton:(UIButton *) (setter)retain 語義:[newValue retain]; [oldValue release]; _websiteButton = newValue;@synthesize,實例變數自動命名為 _propertyName注意:現代開發 (iOS 5+) 全面使用 ARC,以下內容僅供理解底層原理與維護舊代碼參考。
alloc/new/copy/mutableCopy → 持有權 +1 (你負責 release)retain → 持有權 +1release → 持有權 -1,歸零時調用 deallocautorelease → 延遲釋放,下一個 RunLoop 迴圈釋放| 屬性修飾詞 | setter 內部行為 |
|---|---|
assign | 直接賦值,不 retain (基本類型、delegate 弱引用) |
retain | [new retain]; [old release]; _ivar = new; (MRC 標準) |
copy | [new copy]; [old release]; _ivar = copy; (NSString/NSArray/NSDictionary 常用,防止可變對象外部修改) |
| MRC 關鍵字 | ARC 關鍵字 | 說明 |
|---|---|---|
retain | strong | 強引用,延長對象生命週期 |
assign | weak / unsafe_unretained | 弱引用 (不增加引用計數),對象銷毀自動置 nil (weak) |
copy | copy | 複製語義保持不變 |
@synthesize | 自動合成 (可省略) | 實例變數自動為 _propertyName |
.h 中聲明屬性 (@property) 與動作 (IBAction).m 中實作動作邏輯@synthesize 產生的存取器與記憶體語義strong/weak/copy,省略 @synthesize