仿NSNotification&NSNotificationCenter做一個通知

為了更好的理解通知,仿寫了一個通知莺葫。其中用字典存儲觀察者,key是通知的名字枪眉,value是若干個觀察者捺檬。這些觀察者放到一個數組里。也就是value是數組贸铜。

YBNotification


@interface YBNotification : NSObject

@property(nonatomic,copy)NSString *name;

@property(nonatomic,strong,readonly) id object;

@property(nonatomic,readonly,copy)NSDictionary *userInfo;

- (instancetype)initWithName:(NSNotificationName)name object:(nullable id)object userInfo:(nullable NSDictionary *)userInfo;

+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject;
+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

@end


#import "YBNotification.h"

@implementation YBNotification

- (instancetype)initWithName:(NSNotificationName)name object:(nullable id)object userInfo:(nullable NSDictionary *)userInfo
{
    
    self = [super init];
    
    if (self) {
        
        _name = name;
        _object = object;
        _userInfo = userInfo;
        
    }
    return self;
}

+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject
{
    return [self notificationWithName:aName object:anObject userInfo:nil];
}

+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo
{
    return [[self alloc]initWithName:aName object:anObject userInfo:aUserInfo];
}
@end

YBNotificationCenter

@interface YBNotificationCenter : NSObject

+ (YBNotificationCenter *)defaultCenter;

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSString *)aName object:(nullable id)anObject;

- (void)postNotification:(YBNotification *)notification;
- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject;
- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(nullable NSString *)aName object:(nullable id)anObject;

- (id <NSObject>)addObserverForName:(nullable NSString *)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(YBNotification *note))block;

@end
#import "YBNotificationCenter.h"


typedef void(^OperationBlock)(YBNotification *notification);

@interface YBObserverModel : NSObject

@property (nonatomic, strong) id observer;
@property (nonatomic, assign) SEL selector;
@property (nonatomic, copy) NSString *notificationName;
@property (nonatomic, strong) id object;
@property (nonatomic, strong) NSOperationQueue *operationQueue;
@property (nonatomic, copy) OperationBlock block;

@end

@implementation YBObserverModel


@end

@interface YBNotificationCenter ()

@property (nonatomic, strong) NSMutableDictionary *observersDic;

@end

@implementation YBNotificationCenter

static YBNotificationCenter *instance = nil;

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

- (id)copyWithZone:(NSZone *)zone
{
    return instance;
}

+ (YBNotificationCenter *)defaultCenter
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    
    return instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        _observersDic = [NSMutableDictionary dictionary];
        
    }
    return self;
}

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSString *)aName object:(nullable id)anObject
{
    YBObserverModel *model = [YBObserverModel new];
    model.observer = observer;
    model.selector = aSelector;
    model.notificationName = aName;
    model.object = anObject;
    
    //  按照key存儲監(jiān)聽者的數組
    NSMutableArray *modelArray = [self.observersDic objectForKey:aName];
    if (!modelArray) {
        modelArray = [NSMutableArray array];
    }
    
    [modelArray addObject:model];
    [self.observersDic setObject:modelArray forKey:aName];
    

  
    
}

- (id <NSObject>)addObserverForName:(nullable NSString *)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(YBNotification *note))block
{
    YBObserverModel *model = [YBObserverModel new];
    model.notificationName = name;
    model.object = obj;
    model.operationQueue = queue;
    model.block = block;
    
    //  按照key存儲監(jiān)聽者的數組
    NSMutableArray *modelArray = [self.observersDic objectForKey:name];
    if (!modelArray) {
        modelArray = [NSMutableArray array];
    }
    
    [modelArray addObject:model];
    [self.observersDic setObject:modelArray forKey:name];
    
    return nil;
}


- (void)postNotification:(YBNotification *)notification
{

    NSString *name = notification.name;
    NSArray *modelArray = [self.observersDic objectForKey:name];
    for (YBObserverModel *model in modelArray) {
        
        id observer = model.observer;
        SEL selector = model.selector;
        if (model.operationQueue) {
            
           [model.operationQueue addOperationWithBlock:^{
              
               model.block(notification);
               
           }];
            
        }else{
            
             [observer performSelector:selector withObject:notification];
            
        }
        
    }
    
}
- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject
{
    [self postNotificationName:aName object:anObject userInfo:nil];
}

- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo
{
    YBNotification *notification = [[YBNotification alloc]initWithName:aName object:anObject userInfo:aUserInfo];
    [self postNotification:notification];
    
}

- (void)removeObserver:(id)observer
{
    [self removeObserver:observer name:nil object:nil];
}
- (void)removeObserver:(id)observer name:(nullable NSString *)aName object:(nullable id)anObject
{
    
    for (NSString *name in self.observersDic) {
        
        NSMutableArray *modelArray = [self.observersDic objectForKey:name];
        for (YBObserverModel *model in modelArray) {
            
            if (model.observer == observer && [model.notificationName isEqualToString: aName] && model.object == anObject) {
                
                [modelArray removeObject:model];
                
            }
            
        }
        
    }   
}

@end

demo

https://github.com/yinbowang/NSNotificationDemo

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末堡纬,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子蒿秦,更是在濱河造成了極大的恐慌烤镐,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件棍鳖,死亡現場離奇詭異炮叶,居然都是意外死亡,警方通過查閱死者的電腦和手機鹊杖,發(fā)現死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門悴灵,熙熙樓的掌柜王于貴愁眉苦臉地迎上來扛芽,“玉大人骂蓖,你說我怎么就攤上這事〈猓” “怎么了登下?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長叮喳。 經常有香客問我被芳,道長,這世上最難降的妖魔是什么馍悟? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任畔濒,我火速辦了婚禮,結果婚禮上锣咒,老公的妹妹穿的比我還像新娘侵状。我一直安慰自己,他們只是感情好毅整,可當我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布趣兄。 她就那樣靜靜地躺著,像睡著了一般悼嫉。 火紅的嫁衣襯著肌膚如雪艇潭。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天,我揣著相機與錄音蹋凝,去河邊找鬼鲁纠。 笑死,一個胖子當著我的面吹牛鳍寂,可吹牛的內容都是我干的房交。 我是一名探鬼主播,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼伐割,長吁一口氣:“原來是場噩夢啊……” “哼候味!你這毒婦竟也來了?” 一聲冷哼從身側響起隔心,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤白群,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后硬霍,有當地人在樹林里發(fā)現了一具尸體帜慢,經...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年唯卖,在試婚紗的時候發(fā)現自己被綠了粱玲。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡拜轨,死狀恐怖抽减,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情橄碾,我是刑警寧澤卵沉,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站法牲,受9級特大地震影響史汗,放射性物質發(fā)生泄漏。R本人自食惡果不足惜拒垃,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一停撞、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧悼瓮,春花似錦戈毒、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至翅萤,卻和暖如春恐疲,著一層夾襖步出監(jiān)牢的瞬間腊满,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工培己, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留碳蛋,地道東北人。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓省咨,卻偏偏與公主長得像肃弟,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子零蓉,可洞房花燭夜當晚...
    茶點故事閱讀 45,515評論 2 359

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,288評論 25 707
  • 1. Java基礎部分 基礎部分的順序:基本語法笤受,類相關的語法,內部類的語法敌蜂,繼承相關的語法箩兽,異常的語法,線程的語...
    子非魚_t_閱讀 31,664評論 18 399
  • 人們都說要改變世界章喉。 其實是世界改變我們汗贫。 世界塑造了我們,我們僅僅是世界極其微小的一部分秸脱。 僅此而已落包。
    光劍書架上的書閱讀 177評論 0 3
  • 周會之前咐蝇,大BOSS在公司群里發(fā)了這樣一句話: 大家上思考一個開放式問題:如何建立用戶信任感?周會上討論遏片。 嗯嘹害,用...
    飯團兒君閱讀 1,188評論 0 1
  • 一 最近天熱撮竿,我和兒子睡在我媽家里吮便,白天我去練車,我兒子由我媽照顧幢踏。有一天髓需,我學車教練有事,因此我沒有去練車在家里...
    yinwen雨文閱讀 785評論 1 3