class 的isa指针

来源:互联网 发布:编程珠玑 第3版 pdf 编辑:程序博客网 时间:2024/05/16 02:37
查看文档可知
Discussion
The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0.
isa实例变量指向一个描述类的结构体数据。而所有其它实例变量都会被设置为0值。
上一次看内存知道对象指针加8才是自己声明的实例变量的地址。前8个字节一直没有搞清楚是什么。多谢论坛中fantacyleo的指点。其实对象开始8字节就是isa指针。那么他到底是不是呢,我做了一个简单的小程序,输出isa的地址。
  1. #import <Foundation/Foundation.h>

  2. //Person类声明
  3. @interface Person : NSObject
  4. {
  5.     int _age;
  6. }

  7. - (void)setAge:(int)age;//设置_age
  8. - (int)age;//返回_age

  9. - (void*)getIsaAddr;//获取isa成员变量的地址
  10. @end


  11. //Student类声明
  12. @interface Student : Person
  13. {
  14.     int _score;//分数
  15. }

  16. - (void)setScore:(int)score;//设置_score
  17. @end



  18. int main(int argc, const char * argv[])
  19. {
  20.     
  21.     Person *p = [Person new];
  22.     [p setAge:0x88888888];
  23.     
  24.     NSLog(@"p = %p", p);
  25.     NSLog(@"&(p->isa) = %p", [p getIsaAddr]);
  26.     
  27.     
  28.     
  29.     Student *stu = [Student new];
  30.     [stu setAge:0x77777777];
  31.     [stu setScore:0x66666666];
  32.     
  33.     NSLog(@"stu = %p", stu);
  34.     NSLog(@"&(stu->isa) = %p", [stu getIsaAddr]);
  35.     
  36.     
  37.     
  38.     return 0;
  39. }


  40. //Person类的实现
  41. @implementation Person

  42. - (void)setAge:(int)age
  43. {
  44.     _age = age;
  45. }

  46. - (int)age
  47. {
  48.     return _age;
  49. }

  50. - (void*)getIsaAddr
  51. {
  52.     //NSLog(@"size = %u", sizeof(isa));
  53.     return (void*)&isa;
  54. }
  55. @end


  56. //Student类的实现
  57. @implementation Student

  58. - (void)setScore:(int)score
  59. {
  60.     _score = score;
  61. }

  62. @end
复制代码

 
通过观察isa起始地址和对象的起始地址值是一样的,而isa在NSObject中被声明为一个指针,MAC OS系统是64位的,所以指针也就是64的。即占8字节空间。
所以由此可以判断对象的前8个字节就是isa指针。
isa在NSObject.h中声明:
@interface NSObject <NSObject> {
    Class isa  OBJC_ISA_AVAILABILITY;

}

而Class在objc.h中又被声明为:

/// An opaque type that represents an Objective-C class.

typedef struct objc_class *Class;
所以isa是就指向 objc_class结构体的指针。 而后4字节就是person类实例变量age所占用的内存空间;

再观察person类的子类Student对象中实例变量在内存中是怎么分布的

02.png (238.57 KB, 下载次数: 0)

下载附件  保存到相册

2

2014-8-16 21:06 上传

观察发现同样前8字节是isa指针,紧随其后依次存放的是实例变量age和score;

0 0
原创粉丝点击