iOS面试iOS interview面试

iOS底层系列31 -- Notification的底层原理

2022-03-12  本文已影响0人  YanZi_33
image.png
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor redColor];
    //第一步:注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"YanZi" object:nil];
}

//接受到通知,执行回调
- (void)receiveNotification:(NSNotification *)notification {
    NSString *str = notification.userInfo[@"data"];
    NSLog(@"%@",str);
}

//第二步:发送通知
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"YanZi" object:nil userInfo:@{@"data":@"yanzi"}];
}
@end
注册通知部分
typedef struct  Obs {
  id        observer;   //接受消息的对象
  SEL       selector;    //回调方法
  struct Obs    *next;      //下一个Obs的节点指针
  int       retained;  //引用计数
  struct NCTbl  *link;      /* Pointer back to chunk table  */
} Observation;
- (void)addObserver:(id)observer selector:(SEL)selector name:(NSString*)name object:(id)object {
  Observation   *list;
  Observation   *o;
  GSIMapTable   m;
  GSIMapNode    n;
 
  //入参的异常检测......
  
  //保证线程安全
  lockNCTable(TABLE);

  o = obsNew(TABLE, selector, observer);
  //通知名称存在时
  if (name){
      //NAMED是一个哈希表 根据name 取出节点node
      n = GSIMapNodeForKey(NAMED, (GSIMapKey)(id)name);
      if (n == 0){
         //节点为空 创建maptable
         m = mapNew(TABLE);
         name = [name copyWithZone: NSDefaultMallocZone()];
         //将 maptable与name 以键值对的形式 存入NAMED哈希表中
         GSIMapAddPair(NAMED, (GSIMapKey)(id)name, (GSIMapVal)(void*)m);
         GS_CONSUMED(name)
      }else{
         m = (GSIMapTable)n->value.ptr;
      }
      //以object为key 在maptable哈希表中获取指定节点
      n = GSIMapNodeForSimpleKey(m, (GSIMapKey)object);
      if (n == 0){
         o->next = ENDOBS;
         //若节点为空 将object与Observation 以键值对的形式 存入maptable哈希表中
         GSIMapAddPair(m, (GSIMapKey)object, (GSIMapVal)o);
      }else{
         //若节点存在 将Observer添加到Observation单链表中
         list = (Observation*)n->value.ptr;
         o->next = list->next;
         list->next = o;
      }
  }else if (object){
      //name为空 以object为key 从NAMELESS哈希表中取出 节点
      n = GSIMapNodeForSimpleKey(NAMELESS, (GSIMapKey)object);
      if (n == 0){
          o->next = ENDOBS;
          //节点不存在 以object与observation为键值对 存入NAMELESS哈希表中
          GSIMapAddPair(NAMELESS, (GSIMapKey)object, (GSIMapVal)o);
      }else{
          //节点存在 将将Observer添加到Observation单链表中
          list = (Observation*)n->value.ptr;
          o->next = list->next;
          list->next = o;
      }
  }else{
      //当name与object都不存在的情况下 将Observation添加到WILDCARD单链表中
      o->next = WILDCARD;
      WILDCARD = o;
  }
  unlockNCTable(TABLE);
}
image.png
发送通知部分
- (void)postNotificationName:(NSString*)name object:(id)object userInfo:(NSDictionary*)info{
  GSNotification *notification;
  notification = (id)NSAllocateObject(concrete, 0, NSDefaultMallocZone());
  notification->_name = [name copyWithZone: [self zone]];
  notification->_object = [object retain];
  notification->_info = [info retain];
  [self _postAndRelease: notification];
}
- (void) _postAndRelease: (NSNotification*)notification{
  Observation   *o;
  unsigned  count;
  NSString  *name = [notification name];
  id        object;
  GSIMapNode    n;
  GSIMapTable   m;
  GSIArrayItem  i[64];
  GSIArray_t    b;
  GSIArray  a = &b;
  //...
  object = [notification object];
  GSIArrayInitWithZoneAndStaticCapacity(a, _zone, 64, i);
  lockNCTable(TABLE);
  //当name与object均不存在时,遍历WILDCARD链表中的observation对象 添加到数组a中
  for (o = WILDCARD = purgeCollected(WILDCARD); o != ENDOBS; o = o->next){
      GSIArrayAddItem(a, (GSIArrayItem)o);
  }
  //当name不存在,但object存在时,遍历NAMELESS哈希表,将所有observation对象 添加到数组a中
  if (object){
      n = GSIMapNodeForSimpleKey(NAMELESS, (GSIMapKey)object);
      if (n != 0){
      o = purgeCollectedFromMapNode(NAMELESS, n);
      while (o != ENDOBS){
          GSIArrayAddItem(a, (GSIArrayItem)o);
          o = o->next;
      }
     }
   }
  //当name存在时 遍历NAMED哈希表,将所有observation对象 添加到数组a中
  if (name){
      n = GSIMapNodeForKey(NAMED, (GSIMapKey)((id)name));
      if (n){
         m = (GSIMapTable)n->value.ptr;
      }else{
         m = 0;
      }
      if (m != 0){
         n = GSIMapNodeForSimpleKey(m, (GSIMapKey)object);
         if (n != 0){
          o = purgeCollectedFromMapNode(m, n);
          while (o != ENDOBS){
            GSIArrayAddItem(a, (GSIArrayItem)o);
            o = o->next;
          }
        }

        if (object != nil){
          n = GSIMapNodeForSimpleKey(m, (GSIMapKey)nil);
          if (n != 0){
              o = purgeCollectedFromMapNode(m, n);
              while (o != ENDOBS){
                GSIArrayAddItem(a, (GSIArrayItem)o);
                o = o->next;
            }
          }
        }
      }
  }
  unlockNCTable(TABLE);
  //遍历a数组 获取所有Observation中的observe对象 然后通过调用performSelector: 让观察者去调用selector方法(通知回调方法)
  count = GSIArrayCount(a);
  while (count-- > 0){
      o = GSIArrayItemAtIndex(a, count).ext;
      if (o->next != 0){
          NS_DURING{
              //观察者去调用selector方法(通知回调方法)
              [o->observer performSelector: o->selector withObject: notification];
          }
          //...
       }
  }
  lockNCTable(TABLE);
  GSIArrayEmpty(a);
  unlockNCTable(TABLE);
  RELEASE(notification);
}
面试题一:针对addObserver方法,当name为nil,object不为nil时,能否执行通知回调,若name与object都为nil时,发送通知时会发生什么?
面试题二:NSNotification发送是同步的还是异步的?如何实现异步发送通知?
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //第一步:注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"111" object:nil];
}

//接受到通知,执行回调
- (void)receiveNotification:(NSNotification *)notification {
    NSLog(@"%@",[NSThread currentThread]);
    NSLog(@"收到通知");
    sleep(3);
}

//第二步:发送通知
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"111" object:nil userInfo:@{@"data":@"发送通知"}];
    NSLog(@"通知发送完毕");
}
@end
image.png
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //第一步:注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"111" object:nil];
}

//接受到通知,执行回调
- (void)receiveNotification:(NSNotification *)notification {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"%@",[NSThread currentThread]);
        NSLog(@"收到通知");
        sleep(3);
    });
}

//第二步:发送通知
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"111" object:nil userInfo:@{@"data":@"发送通知"}];
    NSLog(@"通知发送完毕");
    NSLog(@"%@",[NSThread currentThread]);
}
@end
image.png
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //第一步:注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"111" object:nil];
}

//接受到通知,执行回调
- (void)receiveNotification:(NSNotification *)notification {
    NSLog(@"%@",[NSThread currentThread]);
    NSLog(@"收到通知");
    sleep(3);
}

//第二步:发送通知
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSNotification *notification = [NSNotification notificationWithName:@"111" object:nil];
    [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostWhenIdle];
    NSLog(@"通知发送完毕");
    NSLog(@"%@",[NSThread currentThread]);
}
@end
image.png
面试题三:NSNotificationQueue与RunLoop之间的关系?
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //第一步:注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"111" object:nil];
}

//接受到通知,执行回调
- (void)receiveNotification:(NSNotification *)notification {
    NSLog(@"%@",[NSThread currentThread]);
    NSLog(@"收到通知");
    sleep(3);
}

//第二步:发送通知
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //NSNotificationQueue依赖RunLoop才能成功触发通知 否则接收不到回调
    //子线程的runLoop需主动获取
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSNotification *notification = [NSNotification notificationWithName:@"111" object:nil];
        [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostWhenIdle];
        [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc]init] forMode:NSRunLoopCommonModes];
        [[NSRunLoop currentRunLoop] run];
    });
}
@end
面试题四:页面销毁时不移除通知会崩溃么?多次添加同一个通知会怎样?多次移除同一个通知会怎样?
上一篇 下一篇

猜你喜欢

热点阅读