[转]iOS isa 浅析

 看见一到面试题讲述一下Objective-C中的isa?完全没听说过,打算小研究一下。

  参考:http://blog.sina.com.cn/s/blog_7a2ffd5c01010nme.html

 

  原来isa类似类似于java中的class,用于动态的获取一个类动态运行时的信息。不过OC比java牛B的是,OC可以在运行时为类添加方法,所以isa比class稍微复杂一点。

  看一下NSObject类的.h  

1 @interface NSObject <NSObject> {
2     Class isa  OBJC_ISA_AVAILABILITY;
3 }

NSObject类作为所有OC对象的父类只有这一个属性isa,我们有必要研究一下,它究竟是什么。


  官方介绍是这样的:

  Every object is connected to the run-time system through its isa instance variable, inherited from the NSObject class. isa identifies the object's class; it points to a structure that's compiled from the class definition. Through isa, an object can find whatever information it needs at runtime such as its place in the inheritance hierarchy, the size and structure of its instance variables, and the location of the method implementations it can perform in response to messages.


  翻译是这样的:

每个对象都是通过isa实例变量连接到运行时系统,从NSObject类继承。Isa标识对象的类;它指向一个结构的类定义编译。

通过ISA可以在运行时找到一个对象的所有信息,继承层次结构中位置它的实例变量的大小和结构以及可以相应消息的方法所实现的位置

可见,通过一个实例对象(Object)的isa,我们可以找到一个对象的所有信息,如类属性的结构,类方法(消息)的入口地址等。

 

  我们再来看一下Class类

复制代码
struct objc_class {
    Class isa  OBJC_ISA_AVAILABILITY;

#if !__OBJC2__
    Class super_class                                        OBJC2_UNAVAILABLE;
    const char *name                                         OBJC2_UNAVAILABLE;
    long version                                             OBJC2_UNAVAILABLE;
    long info                                                OBJC2_UNAVAILABLE;
    long instance_size                                       OBJC2_UNAVAILABLE;
    struct objc_ivar_list *ivars                             OBJC2_UNAVAILABLE;
    struct objc_method_list **methodLists                    OBJC2_UNAVAILABLE;
    struct objc_cache *cache                                 OBJC2_UNAVAILABLE;
    struct objc_protocol_list *protocols                     OBJC2_UNAVAILABLE;
#endif

} OBJC2_UNAVAILABLE;
/* Use `Class` instead of `struct objc_class *` */
复制代码

  我们发现,objc_class结构体中,还有一个Class属性,它是什么作用呢?对象的类(Class)的isa指向了metaclass。通过它我们可以找到静态变量和方法,还有在这个类里动态添加的类别方法。

  Object-C对类对象与实例对象中的 isa 所指向的类结构作了不同的命名:类对象中的 isa 指向类结构被称作 metaclass,metaclass 存储类的static类成员变量与static类成员方法(+开头的方法);实例对象中的 isa 指向类结构称作 class(普通的),class 结构存储类的普通成员变量与普通成员方法(-开头的方法)。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值