zoukankan      html  css  js  c++  java
  • iOS self 和 super 学习

    有人问我 这个问题 回答错了,题干大概是说 [self class] 和 [super class]打印结果 是不是一样的.

    我睁着眼睛说是不一样的 .因为我明明记得 几天前 做 DFS 获取反射基类 用到了这块

    然  pia pia 打脸

    运行一遍 先印证答案:

    在 AppDelegate 里面:

    NSLog(@" %@   %@   %@",[self class],[super class],[self superclass]); 

    打印结果:

    2016-05-18 16:38:14.918 dailylife[34114:1143377]  AppDelegate   AppDelegate   UIResponder

    其实看出来大概的区别了 

    和臆想一样的 是"[self superclass]"   大概以为 最终结果 相同的人 都以为  [super class] 是 [self superclass].

    其实,在开发过程 我真的没有 说因为这个问题出错.

    因为在写 init 方法中 首先会考虑到 override (重用) 的问题 会先 写 [super  class] . 然后 你要实施的重用 写在该行代码的下边. 

    如果当时 我考虑到这个实际运用情况 就不会答错了,真心丢人.

    这就是纯理论 和 实战 对于一问题 不同的诠释吧. 

    那么现在讨论一下 为什么  [self class] 和 [super class]打印的结果相同

    self : 我的理解 就是  当前类的 对象的本身  , 那么 [self class] 就可理解 为 获取当前对象的类. 英文解释:"self refers to the object receiving a message in objective-C programming."

    super : 网上 解释 它是一个编译器的指令符号,我个人现在的理解 它是一种系统级别的 回溯查找 一直找到根,返回的接受者是 [self class] ;英文解释:"super is a flag that tells the compiler to search for the method implementation in a very different place. It begins in the superclass of the class that defines the method where super appears."

    网上特意讲了底层机制: 我就不贴代码了 

    http://chun.tips/blog/2014/11/05/bao-gen-wen-di-objective[nil]c-runtime%281%29[nil]-self-and-super/

    但是 我不认为 网上说的 或者询问方式为类似 "Why does “[self class] == [super class]”?" "或者说 它们两个相等" 之类的 .我只能说他们结果一致 在一定程度上可以替换 . 

    但是滥用 也是有后果的,  会出现一个闭环.

    - (instancetype)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if(self){
         //TODO:
            
        }
        return self;
    }
    - (instancetype)initWithFrame:(CGRect)frame
    {
        self = [self initWithFrame:frame];
        if(self){
         //TODO:
            
        }
        return self;
    }
    - (instancetype)initWithNew:(CGRect)frame
    {
        self = [self initWithFrame:frame];//super as well
        if(self){
         //TODO:
            
        }
        return self;
    }

     我这么写,应该很容易看出来了吧,

    第一种情况,通过 super 编译指令开始回溯,如果还有重写回溯重写 然后继续回溯 一直到基类.  

    第二段代码 则是再次调用当前方法 然后陷入了死循环.(类似这种情况就不能滥用, 并且 我们知道 在 初始化方法里面 尽量不要用点语法 ,不一定什么时候 就造成循环引用, 当然我们知道有这个坑,自己有避免的机制也无所谓啦)

    第三段代码 我们看到 这个时候 方法名不一样  initWithNew:initWithFrame: ,所以 用super  self 都行 ,self 也最终会走到 super 的方法. 大家也可以在工程里面写这几个方法 然后点击进去,或者debug一下看看走的每一步.

    学到什么程度 都会有不懂的问题,也许对别人很简单,自己才会. 丢脸不要紧 只要敢去找回你的颜.

    慢慢积累吧 日子长着呢

  • 相关阅读:
    C#中的abstract、virtual、interface关键字
    tsql字符串截取
    C# byte换算
    apple-mobile-web-app-capable
    Content-Security-Policy
    sqlserver建立连接服务器
    20 ViewPager Demo4自动轮播
    20 ViewPager Demo3指示器
    20ViewPager demo1,2:接收ViewPager展示View的使用
    有没有最好的学习Angularjs2的视频入门体验?
  • 原文地址:https://www.cnblogs.com/someonelikeyou/p/5506360.html
Copyright © 2011-2022 走看看