延时时间的几种方法

等我详细写,最近发现了一些问题

  • 方法1:performSelector
// 1.5s后自动调用self的hideHUD方法
//此方式要求必须在主线程中执行,否则无效。
[self performSelector:@selector(hideHUD) withObject:nil afterDelay:1.5];
  • 方法2:GCD
    这个可以在主线程执行,也可以在子线程执行, 计时最准确的。
    //此方式在可以在参数中选择执行的线程。
   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    // 1.5s后自动执行这个block里面的代码
    self.hud.alpha = 0.0;
});
  • 方法3:NSTimer
//inderval 是指的时间 userinfo 此参数可以为nil,当定时器失效时,由你指定的对象保留和释放该定时器
//当YES时,定时器会不断循环直至失效或被释放,当NO时,定时器会循环发送一次就失效。
//__此方式要求必须在主线程中执行,否则无效。
    self.timermoney=[NSTimer scheduledTimerWithTimeInterval:12 target:self selector:@selector(timerFired:)  userInfo:nil repeats:true];
//——————这里要用到RUNLOOP的事情,这个方法已经加入主线程,所以直接加入ModelCom都满足,
    [[NSRunLoop currentRunLoop]addTimer:self.timermoney forMode:NSDefaultRunLoopMode];
    //立即执行
    [self timerFired:self.timermoney];
    //触发事件
-(void)timerFired:(NSTimer *)theTimer {
    //然后在需要结束的时候停止计时器 ,这个是唯一一个可以将计时器从runloop中移出的方法。
    [self.timermoney invalidate];


//2 通过消息转发
    _target = [NSObject new];
    class_addMethod([_target class],@selector(fire), class_getMethodImplementation([self class], @selector(fire)), "v@:");
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:_target selector:@selector(fire) userInfo:nil repeats:YES];

//3 NSProxy 多重代理实现
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
    
    return [self.target methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation{
    
    [invocation invokeWithTarget:_target];
    
}
    _fyProxy = [FYProxy alloc];
_fyProxy.target = self;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:_fyProxy selector:@selector(fire) userInfo:nil repeats:YES];
    
    
}
  • 4.sleep方式 没用过
//此方式在主线程和子线程中均可执行。是一种阻塞的执行方式,建方放到子线程中,以免卡住界面,
[NSThread sleepForTimeInterval:1.0f]; [self delayMethod];

我没有深入的研究这些延时方法对应的内存泄漏,在我的工作中这么用也没有出现问题,请大牛指出错误

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Object C中创建线程的方法是什么?如果在主线程中执行代码,方法是什么?如果想延时执行代码、方法又是什么? 1...
    AlanGe阅读 5,815评论 0 17
  • GCD简介 GCD 是 libdispatch 的市场名称,而 libdispatch 作为 Apple 的一个库...
    独木舟的木阅读 5,138评论 0 5
  • 线程、进程 1.iOS中的多线程操作、多线程方式? 2.多线程的优点和缺点分别是什么? 答:优点:1、将耗时较长的...
    丶逐渐阅读 5,237评论 0 8
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,268评论 25 709
  • 1.anomaly NOUN anomaly(in sth) a thing, situation, ...
    倦鸟归矣阅读 1,598评论 0 0

友情链接更多精彩内容