NSNotification与NSNotificationCenter

//通知 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.
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值