1.NSNotification:消息或通知
有三个成员变量
- (NSString *)name;
- (id)object;
- (NSDictionary *)userInfo;
通知名称:name,
消息发送者:object,代理在收到NSNotification方法里,可以回调到object
附加信息:userInfo
2.NSNotificationCenter:消息中心
单例模式,需要通过以下类方法访问
[NSNotificationCenter defaultCenter]
3.广播一个通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"aEvent" object:nil];
发送一个附带信息的通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"aEvent" object:nil userInfo:(NSDictionary *)aUserInfo];
aUserInfo是一个字典
直接发送一个通知
[[NSNotificationCenter defaultCenter] postNotification:(NSNotification *)notification]];
4.注册一个通知监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onHandler:) name:@"aEvent" object:nil];
5.移除一个监听
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"aEvent" object:nil];
6.通知要调用的方法
- (void)onHandler:(NSNotification *)notif { NSDictionary *user_info = [notif userInfo]; //执行自定逻辑 }
1.声明一个定时器变量
NSTimer *_timer;
2.启动一个定时器
- (void)startTimer { _timer = [[NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(onTimer) userInfo:nil repeats:NO] retain]; }
定时时间30秒,30秒后调用self的onTimer方法,执行定时操作,不重复
3.停止或中断定时器
- (void)stopTimer { if(_timer != nil){ [_timer invalidate]; //废弃定时器 [_timer release]; _timer = nil; } }
4.定时器调用的方法onTimer
- (void)onTimer { [self stopTimer]; //执行自定义逻辑 }
5.初始化的区别
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
推荐使用scheduled
timerWithTimeInterval初始化时,需要手动addTimer:forMode:,将timer添加到runloop中
而scheduled初始化时,已经使用了默认的mode并添加到了当前runloop中,不需要手动添加
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:NO]; 等效于 NSTimer *timer2 = [NSTimertimerWithTimeInterval:30.0 target:selfselector:@selector(onTimer:) userInfo:nil repeats:NO]; [[NSRunLoopcurrentRunLoop] addTimer:timer2 forMode:NSDefaultRunLoopMode];
6. 立即触发某定时器
- (void)fire;
定时器默认在timeInterval后执行某动作,如果调用上面fire方法,则立即执行制定的动作,并使定时器无效