ios观察者模式之NSNotificationCenter
下面有基本添加通知,发送,接收通知,以及传入参数,解析参数。
first.m
-(void)addObserver{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleMessage:) name:@"test" object:nil]; } -(void)handleMessage:(NSNotification *)nc{ NSString *name = nc.name; NSDictionary *dict = nc.userInfo; Second *object = (Second *)nc.object; NSLog(@"%@ %@ %@",name,dict,object.second); }
second.m
-(void)postNotifacation1{ self.second = @"secondTestString1"; NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"test1",@"1",@"test2",@"2", nil]; [[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:self userInfo:dict]; } -(void)postNotifacation2{ self.second = @"secondTestString2"; [[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:self]; }
调用:
int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... first *first1 = [[first alloc] init]; Second *second = [[Second alloc] init]; [first1 addObserver]; [second postNotifacation1]; [second postNotifacation2]; } return 0; }