这个 AIObservable
类允许您向观察者列表派发事件。它是 观察者 设计模式的一个实现。您甚至可以在通知回调和多个线程或队列中添加和移除观察者。观察者类似于委托,但是您可以有多个观察者。
与 NSNotificationCenter
相比,这个实现有几个优点
dealloc
中调用 removeObserver:
,AIObservable
使用零初始化弱引用。collection:didAddObject:atIndex:
而不是 didAddObject:(NSNotification*)notification
。例如,假设您有一个聊天室。聊天室对象在消息添加、人们加入和离开房间时会派发可观察事件。
@class AIMessage;
@class AIUser;
@protocol AIChatRoomObserver;
@interface AIChatRoom : NSObject
- (void)postMessage:(AIMessage*)message;
// ...
- (void)addObserver:(id<AIChatRoomObserver>)observer;
- (void)removeObserver:(id<AIChatRoomObserver>)observer;
@end
@protocol AIChatRoomObserver
@optional
- (void)chatRoom:(AIChatRoom*)room didGetNewMessage:(AIMessage*)message;
- (void)chatRoom:(AIChatRoom*)room userDidJoin:(AIUser*)user;
- (void)chatRoom:(AIChatRoom*)room userDidLeave:(AIUser*)user;
@end
如您所见,一切都是清晰有意向的,并且观察者方法具有自解释性。以下是实现方法
#import <AIObservable.h>
#import <NSInvocation+AIConstructors.h>
@interface AIChatRoom ()
// We use composition but you could also use inheritance
@property (nonatomic, strong) AIObservable* observable;
@end
@implementation AIChatRoom
- (void)postMessage:(AIMessage*)message {
// ...
// Create an invocation that will be dispatched to every observer
AIChatRoom* chatRoom = self;
NSInvocation* invocation = [NSInvocation invocationWithProtocol:@protocol(AIChatRoomObserver)
selector:@selector(chatRoom:didGetNewMessage:)];
[invocation setArgument:&chatRoom atIndex:2];
[invocation setArgument:&message atIndex:3];
[self.observable notifyObservers:invocation];
}
- (void)addObserver:(id<AIChatRoomObserver>)observer {
[self.observable addObserver:observer];
}
- (void)removeObserver:(id<AIChatRoomObserver>)observer {
[self.observable removeObserver:observer];
}
@end
将源文件复制到您的项目中,或将其添加到 Podfile 中。pod 'AIObservable'