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

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...