OC-NSNotification

原理

就是有人可以发出通知a 然后有人设置为这个通知a的观察者 如果这个通知a被人发出 则接受者就会调用响应的方法
发送通知的同时也可以附带一些参数

一对多 一个通知发出 可以有多个观察者响应

NSNotificationCenter是单例所以只能通过类方法 [NSNotificationCenter defaultCenter]创建

addObserver 添加notification的观察者

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
- //第一个参数是打算调谁的方法 一般是self 
- //第二个参数是当指定的notification发出时打算调什么方法 这个方法在定义的时候要有(NSNotification*)notification作为参数 用来接受notification附带传过来的参数
- //第三个参数是指定notification 也就是notification的名字 
- //第四个参数是前面调的那个方法的参数

postNotificationName 发出notification

- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject /*userInfo:(NSDictionary) 用来传多个参数*/;
- //第一个参数指定是发出一个叫什么名字的notification 第二个是发出的时候要带什么参数 这个参数观察者可用(NSNotification*)notification来接收

例子

//Person.h
@interface Person : NSObject
-(void)weekNotification:(NSNotification*)notification;
@end
//Person.m
#import "Person.h"
#import "dog.h"
@implementation Person
-(id)init
{
    self = [super init];
    if(self != nil)
    {
    //给默认的notification center添加一个观察者 观察一个叫Name的notification 如果有响应 则调用selector中的方法
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(weekNotification:) name:@"Name" object:nil];
    }
    return self;
}
//接收notification时响应的方法
-(void)weekNotification:(NSNotification*)notification
{
    NSLog(@"%S",__func__);
    NSNumber* num = notification.object;
    NSLog(@"Person,%@",num);
}
@end
//dog.h
@interface Dog : NSObject<NSCoding>
{
    int _sleep;
}
-(void)doAction:(id)s;
-(void)openTimer:(NSString*)s;
@end

//dog.m
#import "dog.h"

@implementation Dog
-(id)init{
    self = [super init];
    if(self)
    {
        _sleep = 100;
    }
    return self;
}
-(void)openTimer:(id)obj
{
    NSLog(@"参数:%@",obj);
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(doAction:) userInfo:nil repeats:YES];//添加定时器
    [[NSRunLoop mainRunLoop]run];//让runloop跑起来
}
-(void)doAction:(id)s
{
    NSLog(@"参数%@",s);
    NSLog(@"%s",__func__);
    
    _sleep -=2;
    NSLog(@"_sleep:%d",_sleep);
    if(_sleep < 90)//如果_sleep小于90则发出一个叫name的notification 然后附带一个参数_sleep
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"Name" object:[NSNumber numberWithInteger:_sleep]];
        //如果响应了 可以在这里添加
        //[timer invalidate];//终止timer
    }
}
@end

相关文章

学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习...
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面...
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生...
Can’t connect to local MySQL server through socket \'/v...
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 ...
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服...