您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 學習筆記(四):協定、委派與分類入門

編輯:iOS 開發綜合

Objective-C 裡有三個概念經常一起出現,卻常被混為一談:委派(delegate)、分類(category)與協定(protocol)。這篇把它們各自的角色釐清。

一、委派(Delegate)

委派類似 C 語言的回呼函式:把「某個物件要做的事」交給另一個物件去處理。被託付的那一方就是委託方,負責代替原物件完成工作。

寫程式時要先想清楚兩件事:誰是委託方、託付的內容是什麼。

在 MFC 中,每個程式都必須繼承 CWinApp 並覆寫幾個虛擬函式;而在 Cocoa 中,我們實作 UIApplicationDelegate 就好,不需要繼承——你只需要關注自己在應用生命週期中真正感興趣的那幾個方法。

用指標來理解會更直觀:類別 A 內部握有一個類別 B 的參照,那麼 B 就是 A 的委派物件。A 做完某件事後通知 B,B 呼叫對應方法做出回應。

iOS 開發中最典型的例子就是畫面之間傳值。

@interface A : UIView
@property (nonatomic, retain) id aValueDelegate;
@end

@implementation A
- (void)fa {
    NSString *value = @"hello";
    [aValueDelegate aValue:value];
}
@end

@interface B : UIView
NSString *value;
@end

@implementation B
- (void)aValue:(NSString *)fromValue {
    value = fromValue;
    NSLog(@"%@", value);
}
@end

A *a = [[A alloc] init];
B *b = [[B alloc] init];
a.aValueDelegate = b;   // 把 B 設為 A 的委派物件

二、分類(Category)

分類主要有三個用途:

1. 把一個類別的實作分散到多個檔案中。

2. 建立前向引用,藉此實作私有方法。

3. 實現非正式協定與委派。

@interface NSString (NumberConvenience)
- (NSNumber *)lengthAsNumber;
@end

三、協定(Protocol)

協定類似 C++ 的純虛擬函式(或 Java 的介面):只有宣告、沒有實作,需在採用它的類別中完成實作。

· @optional:可以選擇性實作的方法。

· @required:採用協定的類別必須實作的方法。

不確定某個方法是否被實作時,用 respondsToSelector: 來判斷。

關鍵觀念:協定不是類別,它只是定義了一組「其他物件可以實作的介面」。

非正式協定

用 category 實作,本質上是 NSObject 的一個分類。因為掛在 NSObject 上,任何類別的物件都能當成委派物件使用。判斷某方法是否存在,同樣靠 selector。

@interface NSObject (***Delegate)
// method
@end

正式協定

正式協定是一份有命名的方法清單。與非正式協定的差別在於:它必須在 @interface 中用 <> 明確宣告採用。

@protocol NSCopying
- (id)copyWithZone:(NSZone *)zone;
@end

@interface Car : NSObject <NSCopying> {
    // instance variable
}
// method
@end

四、一個完整的正式協定範例

這個例子示範 Dog 透過協定通知主人(Person)發生了什麼事:

// Dog.h
#import <Foundation/Foundation.h>

@protocol dogBark;

@interface Dog : NSObject {
    int barkCount;
    NSTimer *timer;
}
@property int ID;
@property (assign) id<dogBark> delegate;   // 狗主人
@end

@protocol dogBark <NSObject>
- (void)bark:(Dog *)thisDog count:(int)count;
@end
// Dog.m
#import "Dog.h"

@implementation Dog
@synthesize delegate;

- (id)init {
    if (self = [super init]) {
        // 每秒呼叫一次 updateTimer:
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                 target:self
                                               selector:@selector(updateTimer:)
                                               userInfo:nil
                                                repeats:YES];
    }
    return self;
}

- (void)updateTimer:(id)arg {
    barkCount++;
    NSLog(@"dog bar %d", barkCount);
    [delegate bark:self count:barkCount];   // 通知主人
}
@end
// person.h
#import "Dog.h"

@interface person : NSObject <dogBark> {
    Dog *_dog;
}
@property (retain, nonatomic) Dog *dog;
@end
// person.m
#import "person.h"

@implementation person

- (void)setDog:(Dog *)aDog {
    if (_dog != aDog) {
        [_dog setDelegate:self];   // 自己擔任狗的委派物件
    }
    _dog = aDog;
}

- (void)bark:(Dog *)thisDog count:(int)count {
    NSLog(@"person bark: this dog %d bark %d", [thisDog ID], count);
}
@end
// main.m
#import "Dog.h"
#import "person.h"

int main(int argc, const char *argv[]) {
    @autoreleasepool {
        person *qy = [[person alloc] init];
        Dog *dog = [[Dog alloc] init];
        [dog setID:10];
        [qy setDog:dog];

        while (1) {
            [[NSRunLoop currentRunLoop] run];
        }
    }
    return 0;
}

關於那個 while 迴圈

[[NSRunLoop currentRunLoop] run] 是 Cocoa 的執行迴圈寫法,它會持續阻塞等待事件發生。在等待使用者事件的期間,它會保持運行而不返回。這也是為什麼 NSTimer 能被觸發——它需要一個正在運行的 run loop。

五、@optional 與 @required 的實務差異

@protocol myprotocol <NSObject>
@optional
- (void)print:(int)value;                       // 可選
@required
- (int)printValue:(int)value1 andValue:(int)value2;  // 必須
@end

呼叫可選方法之前,一定要先判斷對方是否實作,否則會崩潰:

SEL sel = @selector(print:);
if ([test respondsToSelector:sel]) {
    [test print:11];
}

也可以用協定型別來宣告變數,讓編譯器協助檢查:

id<myprotocol> protocol = [[[mytest alloc] init] autorelease];
[protocol printValue:200 andValue:300];

重點整理

· 協定宣告了「可以被任何類別實作」的方法。

· 協定不是類別,它定義的是一個介面。

· 類別實作了協定中的方法,就等于實現了該協定。

· 協定常用來實現委派。委派物件是為了協同或代表其他物件而存在的特殊物件。

· 委派的實質,就是「我呼叫自己定義的方法,交由別的類別去實作」。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved