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に対してイベント登録する感じか。