以下是NSNotificationCenter的头文件,请尝试写出NSNotificationCenter.mm实现文件。
@interface NSNotificationCenter :NSObject
@property (class, readonly, strong) NSNotificationCenter *defaultCenter;
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
- (void)postNotification:(NSNotification*)notification;
- (void)postNotificationName:(NSString*)aName object:(nullable id)anObject userInfo:(nullable NSDictionary*)aUserInfo;
- (void)removeObserver:(id)observer;
@end
1.NSNotificationCenter *defaultCenter;是个单例,创建单例的方法如下:
+(NSNotificationCenter *)defaultCenter {
static NSNotification *singleton;
dispatch_once_t onceToken;
dispatch_once (&onceToken,^{//当once=0时执行,为-1时直接跳过,为其它值时会阻塞;
singleton = [[self alloc]initSingleton];
});
return singleton;
}
-(instanceType)initSingleton {
if ([super init]){
_observerArr = [NSMutableArray array];//用来添加通知对象的;
}
return self;
}
2.建立Observer模型
@interface ObserverModel : NSObject
@property(nonatomic,strong)id observer;
@property(nonatomic,assign)SEL selector;
@property(nonatomic,copy)NSString *aName;
@property(nonatomic,strong)id anObject;
@property (nonatomic, strong) NSOperationQueue *operationQueue;//用于是通知是否在主队列;
@property (nonatomic, copy) OperationBlock block;
end
@implementation ObserverModel
end
3.实现- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString*)aName object:(id)anObject {
ObserverModel *model = [ObserverModel alloc]init];
model.observer = observer;
model.selector = aSelector;
model.aName = aName;
model.anObject = anObject;
[self.observerArr addObject:model];
}
4.实现- (void)postNotification:(NSNotification*)notification{
[self.observerArr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {//遍历数组
ObserverModel *model = obj;
id observer = model.observer;
SEL selector = model.selector;
if(!model.operationQueue) {
[observer performSelector:selector withObject:notification];
}
else {
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
model.block(notification);
}];
NSOperationQueue*operationQueue = observerModel.operationQueue;
[operationQueueaddOperation:operation];
}
}
}
5.实现- (void)postNotificationName:(NSString*)aName object:(id)anObject userInfo:(NSDictionary*)aUserInfo
{//Notification可以另外定义这个类包含name,object和userInfo成员;
Notification*notification = [[Notification alloc]initWithName:aName object:anObject userInfo:aUserInfo];
[self postNotification:notification];
}
6.实现- (void)removeObserver:(id)observer name:(NSString*)aName object:(id)anObject
{
[self.observerArr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
observerModel*model = obj;
if(model.observer== observer && [model.aName isEqualToString:aName] && model.object== anObject) {
[self.observerArr removeObject:model];//数组中移除这个通知对象
*stop =YES;
}
}];
}
网友评论