IOS学习笔记之十四:NotificationCenter的使用以及注意事项

来源:互联网 发布:成都好吃网络的蛋糕店 编辑:程序博客网 时间:2024/05/29 15:55
使用方法:
1.让某个人去盯着一个东西,如果这个东西被人在某个地方发了post,那么就去做一件事
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(printName:name: @"messageName" object:nil];

2.给东西发一个post,让盯着这个东西的人去做他们已经安排的事情
[[NSNotificationCenter defaultCenter] postNotificationName:@"messageName" object:nil userInfo: [NSDictionary dictionaryWithObject:@"jory" forKey:@"name"|^Archive.zip]];

注意事项:
1.发送post和收到post的范围:因为NSnotificationCenter defaultCenter是一个单例,所以是全程序都可以收到或者发出这个消息。
2.做的那件事情必须有且只有一个参数。

#import "ViewController.h"


@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *lblName;

@end

@implementation ViewController

- (IBAction)addObserver:(id)sender {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(printName:) name:@"printName" object:nil];

}


- (IBAction)PostNotification:(id)sender {

    [[NSNotificationCenter defaultCenter] postNotificationName:@"printName" object:@"NiKlaus"];

}


- (IBAction)removeObserver:(id)sender {

    [[NSNotificationCenter defaultCenter] removeObserver:self];

    dispatch_async(dispatch_get_main_queue(), ^{

        self.lblName.text = @"NAME";

    });

}


- (void) printName:(NSNotification*) notification {

    id name = [notification object];

    dispatch_async(dispatch_get_main_queue(), ^{

        self.lblName.text = name;

    });

}

@end



0 0
原创粉丝点击