iOS开发技巧

通知机制(NSNotificationCenter/NSNoti

2016-03-09  本文已影响217人  YANGGQ

截图

通知(NSNotification)

  - -(NSString*)name;//通知的名称

  - -(id)object;// 通知发布者(是谁要发布通知)

  - -(NSDictionary*)userInfo;// 一些额外的信息(通知发布者传递给通知接收者的信息内容)
+(instancetype)notificationWithName:(NSString*)aName object:(id)anObject;

+(instancetype)notificationWithName:(NSString*)aName object:(id)anObjectuserInfo:(NSDictionary*)aUserInfo;

-(instancetype)initWithName:(NSString*)name object:(id)objectuserInfo:(NSDictionary*)userInfo;

使用通知的3个步骤



/*
observer:监听器,即谁要接收这个通知
aSelector:收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入
aName:通知的名称。如果为nil,那么无论通知的名称是什么,监听器都能收到这个通知
anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知
*/
-(void)addObserver:(id)observerselector:(SEL)aSelectorname:(NSString*)aName object:(id)anObject;
/*
name:通知的名称
obj:通知发布者
block:收到对应的通知时,会回调这个block
queue:决定了block在哪个操作队列中执行,如果传nil,默认在当前操作队列中同步执行
*/
-(id)addObserverForName:(NSString*)name object:(id)objqueue:(NSOperationQueue*)queue usingBlock:(void(^)(NSNotification*note))block;

-(void)removeObserver:(id)observer;
-(void)removeObserver:(id)observername:(NSString*)aName object:(id)anObject;
- 一般在监听器销毁之前取消注册(如在监听器中加入下列代码):
-(void)dealloc{
  //[superdealloc];  非ARC中需要调用此句
    [[NSNotificationCenterdefaultCenter]removeObserver:self];
}

//设备旋转
UIDeviceOrientationDidChangeNotification
//电池状态改变
UIDeviceBatteryStateDidChangeNotification
// 电池电量改变
UIDeviceBatteryLevelDidChangeNotification
//近距离传感器(比如设备贴近了使用者的脸部)
UIDeviceProximityStateDidChangeNotification

//键盘即将显示
UIKeyboardWillShowNotification
//键盘显示完毕
UIKeyboardDidShowNotification
//键盘即将隐藏
UIKeyboardWillHideNotification
// 键盘隐藏完毕
UIKeyboardDidHideNotification
//键盘的位置尺寸即将发生改变
UIKeyboardWillChangeFrameNotification
//键盘的位置尺寸改变完毕
UIKeyboardDidChangeFrameNotification
上一篇 下一篇

猜你喜欢

热点阅读