您的位置:首页 > 移动开发 > IOS开发

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

2014-11-04 16:01 661 查看
使用方法:
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: