LoginSignup
3
3

More than 5 years have passed since last update.

NSNotificationでaddEventListener、dispatchEvent

Last updated at Posted at 2014-05-30

NSNotificationまわりをラップしただけ。
NSNotification使い方よく忘れるのであると楽な程度。
NSObjectのカテゴリで良いかはあるがとりあえず。

NSObject+Event.h
#import <Foundation/Foundation.h>
@interface NSObject (Event)

- (void)dispatchEvent:(NSString*)eventName userInfo:(NSDictionary*)dic;
- (void)addEventListener:(NSString*)eventName listener:(SEL)sel;
- (void)removeEventListener:(NSString*)eventName;
- (void)allRemoveEventListener;
@end
NSObject+Event.m
#import "NSObject+Event.h"

@implementation NSObject (Event)

- (void)dispatchEvent:(NSString*)eventName userInfo:(NSDictionary*)dic{
    NSNotification *notification = [NSNotification notificationWithName:eventName object:self userInfo:dic];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}

- (void)addEventListener:(NSString*)eventName listener:(SEL)sel{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:sel name:eventName object:nil];
}

- (void)removeEventListener:(NSString*)eventName{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:eventName object:nil];
}

- (void)allRemoveEventListener{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//受け側
- (void)hoge:(NSNotification*)notification{
    [notification userInfo];
}

@end

注意

JSやらAS3やらのECMAScriptのイベントの概念と違うのでそこだけ。
rootに対してイベント登録する感じか。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3