技术文章分类(180)

技术随笔(11)

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;
}

 

posted @ 2014-08-04 10:31  坤哥MartinLi  阅读(171)  评论(0编辑  收藏  举报