zoukankan      html  css  js  c++  java
  • iOS instancetype or id ?

    The id type simply says a method will return a reference to an object. It could be any object of any type.

    The instancetype type says a method will return a reference to an object of the same type as the class on which this method was called. 

    instancetype is a newer feature of Objective-C that basically adds type safety. In many cases, you will see no difference in an app (as you have mentioned). But there are times when instancetype is useful to avoid having to type cast when you call the method.

    For example, imagine a class called SomeClass with a method like this:

    +(id)createSomeClass
    {
      return [[SomeClass alloc] init];
    }
    

      

    Then imagine a subclass of SomeClass called SomeSubclass, that overrides that method like this:

    +(id)createSomeClass
    {
      return [[SomeSubclass alloc] init];
    }
    

      

    Now, if you want to create a SomeSubclass, you would have to do this:

    SomeSubclass *obj = (SomeSubclass*)[SomeSubclass createSomeClass];


    However, if createSomeClass returned instancetype instead of id, then you could write this instead:

    SomeSubclass *obj = [SomeSubclass createSomeClass];


    You will see many people switching to instancetype for return values from any initializer or class creator methods (like the ones shown above). In fact, many of Apple's own APIs have been changed to use instancetype instead of id.

    From: http://raywenderlich.com/forums/viewtopic.php?f=38&t=8959  , thanks !

  • 相关阅读:
    js 模拟表单提交下载文件
    vue 刷新子组件方法解决使用v-if闪屏问题
    Java15-Tomcat&Servlet&HTTP&Request&Response
    JAVA26-SpringBoot-在线教育项目01
    20 Vue-ajax
    19 Vue-JQuery
    18 Vue-Json
    Java 20-Mybatis学习
    17 Vue-ES6语法之Promise、VueX、网络请求封装
    16 Vue-cli脚手架介绍与使用
  • 原文地址:https://www.cnblogs.com/ficow/p/5047307.html
Copyright © 2011-2022 走看看