NSNotificationCenter 的替代品。
// Create your own dispatcher
GDDispatcher *dispatcher = [[GDDispatcher alloc] init];
// or use the shared dispatcher
GDDispatcher *dispatcher = [GDDispatcher sharedDispatcher];
[dispatcher addObserver:self forObject:[Greeting class]
withSelector:@selector(doSthLast:) priority:-5];
[dispatcher addObserver:self forObject:[Greeting class]
withSelector:@selector(doSthFirst:) priority:10];
您可以添加在执行后自动移除的观察者
[dispatcher addObserverOnce:self forObject:[Greeting class]
withSelector:@selector(doSthLast:) priority:-5];
[dispatcher addObserverOnce:self forObject:[Greeting class]
withSelector:@selector(doSthFirst:) priority:10];
[dispatcher dispatchObject:[[Greeting alloc] initWithString:@"Hello"]];
// Logs
// Got greeting first: Hello
// Got greeting last: Hello
- (void)doSthFirst:(Greeting *)greeting {
NSLog(@"Got greeting first: %@", greeting.string);
}
- (void)doSthLast:(Greeting *)greeting {
NSLog(@"Got greeting last: %@", greeting.string);
}
在这个例子中,一个模拟服务从远程服务器获取数据的伪服务。它分发了响应。其他类正在观察 User
类型的对象。如果某个地方的 User
被分发,观察者会接收到通知并且能够执行目标选择器。《fl_dispatcher_add》、《fl_dispatcher_remove》和《fl_dispatcher_dispatch》是 Floc Dispatcher 中一些便利宏。
@interface Example ()
@property(nonatomic, strong) Service *service;
@end
@implementation Example
- (id)init {
self = [super init];
if (self) {
fl_dispatcher_add(self, [User class], @selector(updateWithUser:));
self.service = [[Service alloc] init];
[self.service login];
}
return self;
}
- (void)updateWithUser:(User *)user {
NSLog(@"user.name = %@", user.name);
NSLog(@"user.age = %u", user.age);
}
- (void)dealloc {
fl_dispatcher_remove(self);
}
@end
@implementation Service
- (void)login {
[self performSelector:@selector(remoteServerResponded) withObject:nil afterDelay:0.5];
}
- (void)remoteServerResponded {
User *user = [[User alloc] init];
user.name = @"Joe";
user.age = 28;
fl_dispatcher_dispatch(user);
}
@end
您需要在 Floc-Dispatcher/Classes 中找到所需的源文件。
$ cd path/to/project
$ pod install
打开创建的 Xcode Workspace 文件。