zoukankan      html  css  js  c++  java
  • 单例继承

    情况描述:

    有两个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]];

    }

     

  • 相关阅读:
    Codeforces 985G. Team Players
    关于Hall定理的学习
    bzoj 4561: [JLoi2016]圆的异或并
    UOJ #188. 【UR #13】Sanrd
    LOJ #6053. 简单的函数
    Codeforces F. Cowmpany Cowmpensation
    POJ 3710:Matrix Power Series
    codeforces533E
    luogu2885
    codeforces722E
  • 原文地址:https://www.cnblogs.com/small-octopus/p/4866080.html
Copyright © 2011-2022 走看看