单例继承

情况描述:

有两个ViewController,

FatherViewControllerChildViewController

ChildViewController继承于FatherViewController

FatherViewController实现单例方法:

+ (*)shareInstance{

  static FatherViewController *father = nil;

  static dispatch_once_t once;

  dispatch_once(&once, ^{

    father = [[FatherViewController alloc] init];

  });

  return father;

}

当使用ChildViewController *child = [ChildViewController shareInstance];的时候会出现警告“incompatible pointer types initializing 'ChildViewController *' with an expression of type 'FatherViewController *'

原因就是返回类型是FatherViewController 但是是用ChildViewController来接收,起的冲突。

将FatherViewController单例的返回值改成id或者instancetype就可以消除警告

 

但是,在使用的时候发现,虽然警告不见了,但是child实质还是FatherViewController类,所以还是无法获取ChildViewController

 

修改方法:

将FatherViewController的单例改为

+ (id)shareInstance{

  static NSMutableDictionary *dic = nil;

  static dispatch_once_t once;

  dispatch_once(&once, ^{

    dic = [[NSMutableDictionary alloc] init];

           [dic setObject:[[self alloc] init] forKey:(id<NSCopying>)[self class]];

  });

    return [dic objectForKey:[self class]];

}

 

原文地址:https://www.cnblogs.com/small-octopus/p/4866080.html