消息机制

it2026-04-25  6

http://www.cocoachina.com/ios/20150318/11364.html(消息机制的链接)

通知中心:

#import "KCMainViewController.h" @interface KCMainViewController () @end @implementation KCMainViewController - (void)viewDidLoad {      [ super  viewDidLoad];            [self addObserverToNotificationCenter];       } #pragma mark 添加监听 -(void)addObserverToNotificationCenter{      /*添加应用程序进入后台监听       * observer:监听者       * selector:监听方法(监听者监听到通知后执行的方法)       * name:监听的通知名称(下面的UIApplicationDidEnterBackgroundNotification是一个常量)       * object:通知的发送者(如果指定nil则监听任何对象发送的通知)       */      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:[UIApplication sharedApplication]];            /* 添加应用程序获得焦点的通知监听       * name:监听的通知名称       * object:通知的发送者(如果指定nil则监听任何对象发送的通知)       * queue:操作队列,如果制定非主队线程队列则可以异步执行block       * block:监听到通知后执行的操作       */      NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init];      [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification object:[UIApplication sharedApplication] queue:operationQueue usingBlock:^(NSNotification *note) {          NSLog(@ "Application become active." );      }]; } #pragma mark 应用程序启动监听方法 -(void)applicationEnterBackground{      NSLog(@ "Application enter background." ); } @end   /**   *  添加通知,注意这里设置了附加信息   */ -(void)postNotification{      NSDictionary *userInfo=@{@ "loginInfo" :[NSString stringWithFormat:@ "Hello,%@!" ,_txtUserName.text]};      NSLog(@ "%@" ,userInfo);      NSNotification *notification=[NSNotification notificationWithName:UPDATE_LGOGIN_INFO_NOTIFICATION object:self userInfo:userInfo];      [[NSNotificationCenter defaultCenter] postNotification:notification]; //也可直接采用下面的方法 //    [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_LGOGIN_INFO_NOTIFICATION object:self userInfo:userInfo]; }

转载于:https://www.cnblogs.com/yedandan/p/4350452.html

最新回复(0)