浅谈iOS开发中方法延迟执行的几种方式
2016-03-10 12:47
495 查看
Method1. performSelector方法
Method2. NSTimer定时器
Method3. NSThread线程的sleep
Method4. GCD
公用延迟执行方法- (void)delayMethod{ NSLog(@"delayMethodEnd");}
Method1:performSelector
[self performSelector:@selector(delayMethod) withObject:nil/*可传任意类型参数*/ afterDelay:2.0];
注:此方法是一种非阻塞的执行方式,未找到取消执行的方法。
Method2:NSTimer定时器
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
注:此方法是一种非阻塞的执行方式,
取消执行方法:
- (void)invalidate;即可
Method3:NSThread线程的sleep
[NSThread sleepForTimeInterval:2.0];
注:此方法是一种阻塞执行方式,建议放在子线程中执行,否则会卡住界面。但有时还是需要阻塞执行,如进入欢迎界面需要沉睡3秒才进入主界面时。
没有找到取消执行方式。
Method4:GCD
__block ViewController/*主控制器*/ *weakSelf = self;
dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC)); dispatch_after(delayTime, dispatch_get_main_queue(), ^{ [weakSelf delayMethod]; });`
注:此方法可以在参数中选择执行的线程,是一种非阻塞执行方式。没有找到取消执行方式。
import "ViewController.h" @interface ViewController () @property (nonatomic, strong) NSTimer timer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSLog(@"delayMethodStart"); [self methodOnePerformSelector]; // [self methodTwoNSTimer]; // [self methodThreeSleep]; // [self methodFourGCD]; NSLog(@"nextMethod"); } - (void)methodFiveAnimation{ [UIView animateWithDuration:0 delay:2.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{ } completion:^(BOOL finished) { [self delayMethod]; }]; } - (void)methodFourGCD{ __block ViewController weakSelf = self; dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)); dispatch_after(delayTime, dispatch_get_main_queue(), ^{ [weakSelf delayMethod]; }); } - (void)methodThreeSleep{ [NSThread sleepForTimeInterval:2.0]; } - (void)methodTwoNSTimer{ NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(delayMethod) userInfo:nil repeats:NO]; } - (void)methodOnePerformSelector{ [self performSelector:@selector(delayMethod) withObject:nil/*可传任意类型参数*/ afterDelay:2.0]; } - (void)delayMethod{ NSLog(@"delayMethodEnd"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
相关文章推荐
- iOS 图片编辑——缩放剪切
- iOS小知识(一)
- IOS之NSCache解析
- iOS-----Crash文件分析(一)
- ios学习笔记-属性列表(做一个简单的记事本)
- IOS获取手机存储空间
- iOS-关于@property和@synthesize
- ios开发--多台电脑共用一个开发证书的方法
- iOS Client 与WebSocket 通信(一)
- ios html5 网页取消默认样式
- ios 常用第三方类库
- iOS开发:保持程序在后台长时间运行
- iOS 国际化
- iOS 使用EZAudio库生成wav出错的情况
- iOS开发中的strong、weak、copy
- 自定义iOS控件
- iOS开发- 音效的播放
- cell调用其他控件,造成重叠的解决
- 集成支付宝-iOS
- IOS开发之记录用户登陆状态