萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

iOS 應用開發基礎入門:屬性與方法聲明、Interface Builder 連接、屬性合成與記憶體管理

前言

面向設計師與初學者的 iOS 開發基礎教程。本文以建立簡單聯絡人介面為例,詳細講解類別結構、屬性與方法聲明、IBOutlet/IBAction 連接機制、@synthesize 自動生成存取器、手動記憶體管理 (MRC 時代) 的 retain/release 原理,奠定 Objective-C 物件模型認知基石。

類別結構與聲明

ContactViewController.h — 介面檔


#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);屬性/方法/變數小寫開頭

Interface Builder 連接實操

  1. 開啟 ContactViewController.xib
  2. 按住 Control 從「WWW」按鈕拖線到 .h 檔 @interface 區域
  3. 彈出連接視窗:
    • Connection:Outlet → 輸入 Name: websiteButton → Connect
    • 再次拖線:Connection:Action → 輸入 Name: openWebsite → Connect
  4. Xcode 自動生成上述 @property 與 - (IBAction)... 代碼

IB 連接視窗

屬性合成與實作檔

ContactViewController.m — 實作檔


#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

@synthesize 作用

  • 自動生成 - (UIButton *)websiteButton (getter) 與 - (void)setWebsiteButton:(UIButton *) (setter)
  • setter 內部依據 retain 語義:[newValue retain]; [oldValue release]; _websiteButton = newValue;
  • 現代 Xcode (LLVM 4.0+) 預設自動合成,可省略 @synthesize,實例變數自動命名為 _propertyName

記憶體管理基礎 (MRC 歷史背景)

注意:現代開發 (iOS 5+) 全面使用 ARC,以下內容僅供理解底層原理與維護舊代碼參考。

引用計數規則

  • alloc/new/copy/mutableCopy → 持有權 +1 (你負責 release)
  • retain → 持有權 +1
  • release → 持有權 -1,歸零時調用 dealloc
  • autorelease → 延遲釋放,下一個 RunLoop 迴圈釋放

屬性 setter 語義對應

屬性修飾詞setter 內部行為
assign直接賦值,不 retain (基本類型、delegate 弱引用)
retain[new retain]; [old release]; _ivar = new; (MRC 標準)
copy[new copy]; [old release]; _ivar = copy; (NSString/NSArray/NSDictionary 常用,防止可變對象外部修改)

現代化對應 (ARC 時代)

MRC 關鍵字ARC 關鍵字說明
retainstrong強引用,延長對象生命週期
assignweak / unsafe_unretained弱引用 (不增加引用計數),對象銷毀自動置 nil (weak)
copycopy複製語義保持不變
@synthesize自動合成 (可省略)實例變數自動為 _propertyName

實戰小結

  1. 在 .h 中聲明屬性 (@property) 與動作 (IBAction)
  2. 用 IB 連接視圖元件與代碼 (Outlet/Action)
  3. 在 .m 中實作動作邏輯
  4. 理解 @synthesize 產生的存取器與記憶體語義
  5. 現代開發:開啟 ARC,使用 strong/weak/copy,省略 @synthesize
copyright © 萬盛學電腦網 all rights reserved