延时执行的三种方式:performSelectorXXX方法、GCD中延时函数、创建定时器

 
第一种方式:NSObject分类当中的方法,延迟一段时间调用某一个方法

@interface NSObject (NSDelayedPerforming)

※延时调用在当前线程使用特定模式的方法(如果数组没有数据或者参数为nil,则不会调用selector中方法)

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes;

※延时调用在当前线程使用默认模式的方法

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;

※取消某一个延时调用请求

+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument;

※取消全部的延时调用请求

+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;

@end

-============================================================================

第二种方式:GCD当中的方法

间隔时间宏定义:NSEC纳秒、MSEC毫秒、 USEC微妙、 SEC秒、 PER每

#define NSEC_PER_SEC                     //每一秒有多少纳秒

#define NSEC_PER_MSEC                  //每一毫秒有多少纳秒

#define USEC_PER_SEC                    //每一秒有多少微妙(注意:在纳秒的基础上)

#define NSEC_PER_USEC                     //每一微秒有多少纳秒

开始时间宏定义:

#define DISPATCH_TIME_NOW            //当前时间

#define DISPATCH_TIME_FOREVER        //永久时间(无限循环)

相关方法:

※时间变量类型

typedef uint64_t dispatch_time_t;

※创建延时间隔时间(参数:宏定义开始时间、设置秒数*宏定义的间隔时间)

dispatch_time(dispatch_time_t when, int64_t delta);

※队列变量类型(主队列、默认全局队列、自定义队列)

dispatch_queue_t  queue

※执行延时函数操作(参数:延迟时间、队列、block操作)

dispatch_after(dispatch_time_t when,dispatch_queue_t  queue,dispatch_block_t block);

===================================================================================

第三种方式:创建定时器

@interface NSTimer : NSObject

属性:

※设置定时器的启动时间,管理定时器的启动和停止

@property (copy) NSDate *fireDate;

※只读属性,获取时间间隔

@property (readonly) NSTimeInterval timeInterval;

※这是7.0之后的一个新特性,由于NSTimer不精确,通过它设置误差范围

@property NSTimeInterval tolerance ;

※只读属性,获取定时器是否有效

@property (readonly, getter=isValid) BOOL valid;

※参数信息

@property (readonly, retain) id userInfo;

方法:

※创建定时器的time-类方法,需要手动fire开启定时器,将执行方法封装到NSInvocation中

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

※创建定时器的time-类方法,需要手动fire开启定时器

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

※创建定时器的scheduled-类方法,不需要手动fire开启定时器,将执行方法封装到NSInvocation中

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

※创建定时器的scheduled-类方法,不需要手动fire开启定时器

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

※创建定时器的实例方法,会在指定时间开启定时器

- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep;

※开启定时器

- (void)fire;

※使定时器失效,将定时器从循环池移除掉

- (void)invalidate;

@end

04-18 13:40