//通知 NSNotification
//NSNotification是一个model,与日常项目中的model是一样的,比如你的Movie,Card.代表一个通知.包含name(NSString),object(id),userinfo(NSDictionary),提供了创建方法.以及查看通知信息的方法.
//NSNotification是信息.需要通过通知中心发布.
//NSNotificationCenter主要负责通知的处理
#import "RootViewController.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//通知 NSNotification
//NSNotification是一个model,与日常项目中的model是一样的,比如你的Movie,Card.代表一个通知.包含name(NSString),object(id),userinfo(NSDictionary),提供了创建方法.以及查看通知信息的方法.
//NSNotification是信息.需要通过通知中心发布.
//NSNotificationCenter主要负责通知的处理
self.view.backgroundColor = [UIColor redColor];
//标准的写法.应该创建一个view的子类,在loadView方法中,吧self.view设置为view的子类对象,此处我们简写,吧button的创建写在ViewDidLoad之中.
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
[btn setFrame:CGRectMake(100, 100, 100, 100)];
[btn setTitle:@"bufangjia" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(postNotification) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
NSNotificationCenter *notificationcenter = [NSNotificationCenter defaultCenter];
[notificationcenter addObserver:self selector:@selector(aa:) name:@"不放假" object:@"张三"];
[notificationcenter addObserver:self selector:@selector(cc:) name:UIApplicationDidEnterBackgroundNotification object:nil];
}
- (void)cc:(NSNotification *)a
{
NSLog(@"%@",a.name);
NSLog(@"进入后台");
}
- (void)aa:(NSNotification *)a
{
NSLog(@"%@",a.name);
}
- (void)postNotification
{
NSLog(@"button点击事件");
NSNotificationCenter *notificationcenter = [NSNotificationCenter defaultCenter];
[notificationcenter postNotificationName:@"不放假" object:@"张三"];
//Notification 同步,看btn的执行顺序
NSLog(@"点击结束");
}
//当控制器被释放掉的时候,一定要将通知remove掉,不然会引起程序crash
- (void)dealloc
{
NSNotificationCenter *notificationcenter = [NSNotificationCenter defaultCenter];
[notificationcenter removeObserver:self name:nil object:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}