從 Java 的角度來理解:@protocol 相當於 Java 的介面定義,用法也類似。
下面是一個實驗範例。首先定義 protocol 並由類別實作此介面:
@protocol mytestClass <NSObject>
- (void)callback:(int)num;
@end
@interface DiscoveryController : UIViewController <mytestClass> {
UIImageView *imageView;
}
- (UIImage *)getImageFromURL:(NSString *)fileURL;
@end
MyCallBack 中保存從其他類別傳入的 delegate,需要時進行回調:
@interface MyCallBack : NSObject {
id<mytestClass> delegate;
}
@property(nonatomic, retain) id<mytestClass> delegate;
- (void)setRun;
@end
MyCallBack.m:
#import "MyCallBack.h"
@implementation MyCallBack
@synthesize delegate;
- (void)runThread {
NSLog(@"我在運行");
[NSThread sleepForTimeInterval:2];
[delegate callback:1];
}
- (void)setRun {
NSThread *callbackthread = [[NSThread alloc] initWithTarget:self selector:@selector(runThread) object:nil];
[callbackthread start];
}
@end
這裡透過執行緒進行非同步回調,能讓程式流程更加直觀。
呼叫時,建立 MyCallBack 物件並把自己設為 delegate,再啟動即可:
MyCallBack *vv = [[MyCallBack alloc] init]; vv.delegate = self; [vv setRun];
凡是需要用到的類別,實作這個 protocol 並傳送指標即可。這種模式正是 Objective-C 中 delegate 回調機制的核心用法。