手机
当前位置:查字典教程网 >编程开发 >IOS开发 >iOS 四种回调方法总结
iOS 四种回调方法总结
摘要:最近对做IOS项目遇到回调,抽空把相关资料整理下,以下是整理内容:回调回调就是将一段可执行的代码和一个特定的事件绑定起来。当特定的事件发生时...

最近对做IOS 项目遇到回调,抽空把相关资料整理下,以下是整理内容:

回调

回调就是将一段可执行的代码和一个特定的事件绑定起来。当特定的事件发生时,就会执行这段代码。

在Objective-C中,有四条途径可以实现回调。

目标-动作对

在程序开始定等待前,要求“当时间发生时,向指定的对象发送某个特定的信息”。这里接收消息的对象是目标,消息的选择器是动作。

辅助对象

在程序开始等待之前,要求“当时间发生时,向遵守相应协议的辅助对象发送消息”。委托对象和数据源是常见的辅助对象。

通知

苹果公司提供了一种称为通知中心的对象。在程序开始等待前,就可以告知通知中心”某个对象正在等待某些特定的通知。当其中的某个通知出现时,向指定的对象发送特定的消息”。当事件发生时,相关的对象会向通知中心发布通知,然后再由通知中心将通知转发给正在等待通知的对象。

Block对象

Block是一段可执行代码。在程序开始等待前,声明一个Block对象,当事件发生时,执行这段Block对象。

NSRunLoop

iOS中有一个NSRunLoop类,NSRunLoop实例会持续等待着,当特定的事件发生时,就会向相应的对象发送消息。NSRunLoop实例会在特定的事件发生时触发回调。

循环

实现回调之前要先创建一个循环:

int main(int argc, const char * argv[]) { @autoreleasepool { [[NSRunLoop currentRunLoop]run]; } return 0; }

目标-动作对

创建一个拥有NSRunLoop对象和NSTimer对象的应用程序。每隔两秒,NSTimer对象会向其目标发送指定的动作消息,创建一个新的类,名为BNRLogger,为NSTimer对象的目标。

在BNRLogger.h中声明动作方法:

#import <Foundation/Foundation.h> @interface BNRLogger : NSObject<NSURLSessionDataDelegate> @property(nonatomic) NSDate *lastTime; -(NSString *) lastTimeString; -(void)updateLastTime: (NSTimer *) t; @end

在BNRLogger.m中实现方法:

#import "BNRLogger.h" @implementation BNRLogger -(NSString *)lastTimeString { static NSDateFormatter *dateFormatter=nil; if(!dateFormatter) { dateFormatter =[[NSDateFormatter alloc]init]; [dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; NSLog(@"created dateFormatter"); } return [dateFormatter stringFromDate:self.lastTime]; } -(void)updateLastTime:(NSTimer *)t { NSDate *now=[NSDate date]; [self setLastTime:now]; NSLog(@"Just set time to %@",self.lastTimeString); } @end

main.m中创建一个BNRLogger实例:

#import <Foundation/Foundation.h> #import "BNRLogger.h" int main(int argc, const char * argv[]) { @autoreleasepool { BNRLogger *logger=[[BNRLogger alloc]init]; __unused NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:2.0 target:logger selector:@selector(updateLastTime:) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop]run]; } return 0; }

辅助对象

我的上一篇Blog已经写过NSURLSession方法的使用,那么辅助对象回调的使用,将BNRLogger对象成为NSURLSession的委托对象,特定的事件发生时,该对象会向辅助对象发送消息。

main.m中创建一个NSURL对象以及NSURLRequest对象。然后创建一个NSURLSession对象,设置BNRLogger的实例为它的

委托对象:

#import <Foundation/Foundation.h> #import "BNRLogger.h" int main(int argc, const char * argv[]) { @autoreleasepool { BNRLogger *logger=[[BNRLogger alloc]init]; //URL是一张图片的下载链接 NSURL *url = [NSURL URLWithString:@"http://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=http%3A%2F%2Fimg.xiazaizhijia.com%2Fuploads%2F2016%2F0914%2F20160914112151862.jpg&thumburl=http%3A%2F%2Fimg4.imgtn.bdimg.com%2Fit%2Fu%3D2349180720%2C2436282788%26fm%3D11%26gp%3D0.jpg"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; __unused NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:logger delegateQueue:[NSOperationQueue mainQueue]]; __unused NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:2.0 target:logger selector:@selector(updateLastTime:) userInfo:nil repeats:YES]; //4.根据会话对象创建一个Task(发送请求) NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request]; //5.执行任务 [dataTask resume]; [[NSRunLoop currentRunLoop]run]; } return 0; }

BNRLogger.h中,声明NSURLSessionDataDelegate协议:

#import <Foundation/Foundation.h> @interface BNRLogger : NSObject<NSURLSessionDataDelegate> @property (nonatomic, strong) NSMutableData *responseData; @property(nonatomic) NSDate *lastTime; -(NSString *) lastTimeString; -(void)updateLastTime: (NSTimer *) t; @end

BNRLogger.m中,有NSURLSession的代理方法,具体可以看NSURLSession:

#import "BNRLogger.h" @implementation BNRLogger -(NSMutableData *)responseData { if (_responseData == nil) { _responseData = [NSMutableData data]; } return _responseData; } -(NSString *)lastTimeString { static NSDateFormatter *dateFormatter=nil; if(!dateFormatter) { dateFormatter =[[NSDateFormatter alloc]init]; [dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; NSLog(@"created dateFormatter"); } return [dateFormatter stringFromDate:self.lastTime]; } -(void)updateLastTime:(NSTimer *)t { NSDate *now=[NSDate date]; [self setLastTime:now]; NSLog(@"Just set time to %@",self.lastTimeString); } //1.接收到服务器响应的时候调用该方法 -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { //在该方法中可以得到响应头信息,即response NSLog(@"didReceiveResponse--%@",[NSThread currentThread]); NSLog(@"响应"); //注意:需要使用completionHandler回调告诉系统应该如何处理服务器返回的数据 //默认是取消的 /* NSURLSessionResponseCancel = 0, 默认的处理方式,取消 NSURLSessionResponseAllow = 1, 接收服务器返回的数据 NSURLSessionResponseBecomeDownload = 2,变成一个下载请求 NSURLSessionResponseBecomeStream 变成一个流 */ completionHandler(NSURLSessionResponseAllow); } //2.接收到服务器返回数据的时候会调用该方法,如果数据较大那么该方法可能会调用多次 -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { NSLog(@"didReceiveData--%@",[NSThread currentThread]); NSLog(@"返回"); //拼接服务器返回的数据 [self.responseData appendData:data]; } //3.当请求完成(成功|失败)的时候会调用该方法,如果请求失败,则error有值 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"didCompleteWithError--%@",[NSThread currentThread]); NSLog(@"完成"); if(error == nil) { //解析数据 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil]; NSLog(@"%@",dict); } } @end

通知

当系统时区发生变化时,会向通知中心发布NSSystemTimeZoneDidChangeNotification通知,然后通知中心会将该通知转发给相应的观察者。

main.m中将BNRLogger实例注册为观察者,系统时区设置发生变化可以收到相应的通知:

//在”辅助对象”方法应用程序中的main.m中加入这行代码 [[NSNotificationCenter defaultCenter]addObserver:logger selector:@selector(zoneChange:) name:NSSystemTimeZoneDidChangeNotification object:nil];

在BNRLogger.m中实现该方法:

//在”辅助对象”方法应用程序中的BNRLogger.m中加入这行代码 -(void)zoneChange:(NSNotification *)note { NSLog(@"The system time zone has changed!"); }

Block回调

把上面所讲的“通知”方法应用程序main.m中的:

[[NSNotificationCenter defaultCenter]addObserver:logger selector:@selector(zoneChange:) name:NSSystemTimeZoneDidChangeNotification object:nil];

改为:

[[NSNotificationCenter defaultCenter]addObserverForName:NSSystemTimeZoneDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){ NSLog(@"The system time zone has changed!"); }];

“通知”方法应用程序BNRLogger.m中的这个方法去掉:

-(void)zoneChange:(NSNotification *)note { NSLog(@"The system time zone has changed!"); }

总结

对于只做一件事情的对象(例如),使用目标-动作对。 对于功能更复杂的对象(例如NSURLSession),使用辅助对象。最常见的辅助对象类型是委托对象。 对于要触发多个(其他对象中的)回调的对象(例如NSTimeZone),使用通知。 Block实现回调使代码便于阅读。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

【iOS 四种回调方法总结】相关文章:

iOS获取网络类型的方法汇总

iOS6中ARC 下两种释放对象的方法

iOS 检测网络状态的两种方法

iOS 实现多代理的方法及实例代码

iOS文字渐变色效果的实现方法

iOS关闭虚拟键盘方法汇总

iOS7 毛玻璃特效代码

IOS绘制虚线的方法总结

iOS 开发常用宏总结

IOS获取各种文件目录路径的方法

精品推荐
分类导航