- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章iOS 四种回调方法总结由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
最近对做IOS 项目遇到回调,抽空把相关资料整理下,以下是整理内容:
回调 。
回调就是将一段可执行的代码和一个特定的事件绑定起来。当特定的事件发生时,就会执行这段代码。 在Objective-C中,有四条途径可以实现回调.
目标-动作对 。
在程序开始定等待前,要求“当时间发生时,向指定的对象发送某个特定的信息”。这里接收消息的对象是目标,消息的选择器是动作.
辅助对象 。
在程序开始等待之前,要求“当时间发生时,向遵守相应协议的辅助对象发送消息”。委托对象和数据源是常见的辅助对象.
通知 。
苹果公司提供了一种称为通知中心的对象。在程序开始等待前,就可以告知通知中心”某个对象正在等待某些特定的通知。当其中的某个通知出现时,向指定的对象发送特定的消息”。当事件发生时,相关的对象会向通知中心发布通知,然后再由通知中心将通知转发给正在等待通知的对象.
Block对象 。
Block是一段可执行代码。在程序开始等待前,声明一个Block对象,当事件发生时,执行这段Block对象.
NSRunLoop 。
iOS中有一个NSRunLoop类,NSRunLoop实例会持续等待着,当特定的事件发生时,就会向相应的对象发送消息。NSRunLoop实例会在特定的事件发生时触发回调.
循环 。
实现回调之前要先创建一个循环:
1
2
3
4
5
6
|
int
main(
int
argc,
const
char
* argv[]) {
@autoreleasepool {
[[NSRunLoop currentRunLoop]run];
}
return
0;
}
|
目标-动作对 。
创建一个拥有NSRunLoop对象和NSTimer对象的应用程序。每隔两秒,NSTimer对象会向其目标发送指定的动作消息,创建一个新的类,名为BNRLogger,为NSTimer对象的目标。 在BNRLogger.h中声明动作方法:
1
2
3
4
5
6
7
8
9
|
#import <Foundation/Foundation.h>
@interface BNRLogger : NSObject<NSURLSessionDataDelegate>
@property(nonatomic) NSDate *lastTime;
-(NSString *) lastTimeString;
-(
void
)updateLastTime: (NSTimer *) t;
@end
|
在BNRLogger.m中实现方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#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实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#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的实例为它的 。
委托对象:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#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协议:
1
2
3
4
5
6
7
8
9
10
|
#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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
#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实例注册为观察者,系统时区设置发生变化可以收到相应的通知:
1
2
|
//在”辅助对象”方法应用程序中的main.m中加入这行代码
[[NSNotificationCenter defaultCenter]addObserver:logger selector:@selector(zoneChange:) name:NSSystemTimeZoneDidChangeNotification object:nil];
|
在BNRLogger.m中实现该方法:
1
2
3
4
5
|
//在”辅助对象”方法应用程序中的BNRLogger.m中加入这行代码
-(
void
)zoneChange:(NSNotification *)note
{
NSLog(@
"The system time zone has changed!"
);
}
|
Block回调 。
把上面所讲的“通知”方法应用程序main.m中的:
1
|
[[NSNotificationCenter defaultCenter]addObserver:logger selector:@selector(zoneChange:) name:NSSystemTimeZoneDidChangeNotification object:nil];
|
改为:
1
2
3
|
[[NSNotificationCenter defaultCenter]addObserverForName:NSSystemTimeZoneDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
NSLog(@
"The system time zone has changed!"
);
}];
|
“通知”方法应用程序BNRLogger.m中的这个方法去掉:
1
2
3
4
|
-(
void
)zoneChange:(NSNotification *)note
{
NSLog(@
"The system time zone has changed!"
);
}
|
总结 。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持! 。
最后此篇关于iOS 四种回调方法总结的文章就讲到这里了,如果你想了解更多关于iOS 四种回调方法总结的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我正在研究 learnyounode 的 HTTP 客户端作业。 我想知道为什么控制台记录来自response.on(“end”,callback)的数据仅输出预期输出的最后一部分,而控制台记录来自r
我正在尝试创建一个对象列表(在我的示例中为 List),我在其中使用 json 将对象添加到此列表,但该列表仍为空。这是我的代码: public List readCardsFromJson() {
我有一个 JavaScript 函数“print_something”,它在大约 300 个 jsp 帮助页面中实现。我发现这个“print_something”函数必须被纠正。所以我正在寻找一个不更
有 2 个 HTML 下拉列表,一个用于 12 小时时间,一个用于每小时 5 分钟的时间间隔。 .. 1 .. 12 .. 0 .. 55 .. 一直在尝试使用 if/
我有一个 A 类,我打算在它与设备驱动程序交互时将其放入共享库中。 我有一个 B 类,将来可能是 C、D、E...,它将使用共享库中的 A 类。 我想要在类 A 中设置回调函数的功能,以便当特定事件发
我需要能够在处理完 Observable.next() 之后执行回调。 我有一个组件“A”,它有一个主题使用 Subject.next() 发送通知。我有一个组件“B”,它订阅了 Subject.as
我有一张在顶部和底部单元格下方带有阴影的表格(此处使用 Matt Gallagher 的解决方案:http://cocoawithlove.com/2009/08/adding-shadow-effe
有人可以向我解释一下为什么这段代码有效 renderSquare(i) { return ( this.handleClick(i)} /> ); } 但
我可以让两个不同的客户端监听相同的 WCF 回调并让它们都接收相同的数据而不必进行两次处理吗? 最佳答案 不是真的 - 至少不是直接的。你所描述的听起来很像发布/订阅模式。 WCF 服务基本上在任何给
我是 SignalR 的新手,如果这个问题太明显,我深表歉意,但我在文档中找不到任何答案。 这是我的代码。 /*1*/ actions.client.doActionA = function (r
我有这个应用程序,您可以在其中输入一些文本并按下一个按钮,将此文本添加到自定义小部件中。这是代码: import 'dart:core'; import 'package:flutter/materi
我读到当您还想使用模型回调时不能使用 Keras 进行交叉验证,但是 this post表明这毕竟是可能的。但是,我很难将其纳入我的上下文。 为了更详细地探讨这个问题,我正在关注 machinelea
我尝试在重力表单中提交表单失败后运行一些 jQuery 代码,也就是验证发现错误时。 我尝试使用 Ajax:complete 回调,但它根本不触发。 我尝试运行的代码基本上将监听器添加到选择下拉列表中
我有一个 $image,我 .fadeIn 和 .fadeOut,然后 .remove .fadeOut 完成。这是我的代码: $image .fadeIn() .fadeOut(func
我正在处理一个自定义文件路径类,它应该始终执行一个函数 写入相应的系统文件及其文件对象后 关闭。该函数将文件路径的内容上传到远程位置。 我希望上传功能完全在用户的幕后发生 透视,即用户可以像使用其他任
这里是 javascript 新手,所以回调在我的大脑中仍然有点不确定。 我想做的是:给定一个“菜单”,它是一个 objectId 数组,查询与该 objectId 相对应的每个 foodItem,获
我正在学习回调,我编写了以下代码: var http = require('http'); var str = ""; var count = 2; function jugglingAsync(ca
这是我的困境,我有一系列被调用的函数,我正在使用回调函数在它们完成时执行函数。回调返回一个值并且效果也很好,我的问题是当我向回调添加参数时我无法再访问返回值。这是一个有效的例子: function m
This question already has answers here: Explanation of function pointers (4个答案) 上个月关闭。 如何将函数指针作为参数传递
我无法让以下代码工作。假设 ajax 调用有效,并且 msg['username'] 预设为 'john'。我想我对如何将变量传递给回调感到困惑。编辑:我认为我的主要困惑是如何从 Ajax 中获取“m
我是一名优秀的程序员,十分优秀!