从java角度来理解
class="p1">@protocol 相当于 java 的接口定义,用法也一样
下面是试验例子
@protocol mytestClass <NSObject> - (void) callback:(int) num; @end @interface DiscoveryController : UIViewController<mytestClass>{ UIImageView *imageView; } -(UIImage *) getImageFromURL:(NSString *)fileURL; @end
在这里定义了protocol并由类
DiscoveryController实现此接口
@interface MyCallBack : NSObject { id<mytestClass> deleage; } @property(nonatomic,retain) id<mytestClass> deleage; - (void)setRun; @end
MyCallBack中保存从其它类传过来的
deleage当需要时进行回调。
// // MyCallBack.m // ACMobile // // Created by mr.liang on 15/1/22. // Copyright (c) 2015年 mr.liang. All rights reserved. // #import "MyCallBack.h" @implementation MyCallBack @synthesize deleage; - (void) runThread { NSLog(@"我在运行"); [NSThread sleepForTimeInterval:2]; [deleage callback:1]; } - (void)setRun { NSThread *callbackthread = [[NSThread alloc] initWithTarget:self selector:@selector(runThread) object:nil]; [callbackthread start]; } @end
MyCallBack *vv = [[MyCallBack alloc] init]; vv.deleage = self; [vv setRun];
需要用到protocol的地方实现这个protocol并传送指针;
互联网的一点事 www.yidin.net