zoukankan      html  css  js  c++  java
  • 理解Objective C 中id

    什么是id,与void *的区别

    id在Objective C中是一个类型,一个complier所认可的Objective C类型,跟void *是不一样的,比如一个 id userName, 和void *pUserName,[userName print] 是可以的,但[pUserName print] 在编译时就会报错,因为ObjeciveC的编译器看到id,会假定它可以接受任何message,虽然在runtime时可能并不是这样的,但pUserName并不是Objective C类型,编译器就会报错,但是void *有可能时可以接收print message的。

    /**
     * Type for Objective-C objects.
     */
    typedef struct objc_object
    {
    	/**
    	 * Pointer to this object's class.  Accessing this directly is STRONGLY
    	 * discouraged.  You are recommended to use object_getClass() instead.
    	 */
    #ifndef __OBJC_RUNTIME_INTERNAL__
    	__attribute__((deprecated))
    #endif
    	Class isa;
    } *id;

    id 与 NSObject *的区别

    id与instanceType

    什么时候应该用id

    1. 当需要创建一个Collection类或者方法,这些类或方法接收各种不同类型时,比如NSArray中即可以接收NSString,又可以NSObject,还可以NSProxy,就需要用id;
    2. 当需要把某些信息作为context或者token 对象传出给public API使用,而caller不能改变所传出的对象时,就可以使用id作为类型;

    init 方法的实现

    convience constructor 

    http://tewha.net/2013/02/why-you-should-use-instancetype-instead-of-id/

    http://stackoverflow.com/questions/7903954/why-use-id-when-we-can-just-use-nsobject

  • 相关阅读:
    Computer Vision: Algorithms and ApplicationsのImage processing
    LOJ6079「2017 山东一轮集训 Day7」养猫
    网络七层协议及其作用
    观察者模式深度剖析
    NIO 中的读和写
    NIO的通道和缓冲区
    NIO简介
    使用OutputStream向屏幕上输出内容
    对象的序列化
    PushBackInputStream回退流
  • 原文地址:https://www.cnblogs.com/whyandinside/p/3663169.html
Copyright © 2011-2022 走看看