A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© xiniuniu 中级黑马   /  2014-8-16 21:10  /  6009 人查看  /  8 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

查看文档可知
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对象中实例变量在内存中是怎么分布的
观察发现同样前8字节是isa指针,紧随其后依次存放的是实例变量age和score;


评分

参与人数 2技术分 +1 黑马币 +14 收起 理由
★彬★卍囧神 + 1 + 2
fantacyleo + 12 很给力!送上2个技术分

查看全部评分

8 个回复

倒序浏览
好贴,赞一个
回复 使用道具 举报
分没收到哦!!{:3_62:}
回复 使用道具 举报

版主才有权限直接给技术分,我只能给你黑马币,可以换技术分的,6黑马币=1技术分
回复 使用道具 举报
fantacyleo 发表于 2014-8-17 00:15
版主才有权限直接给技术分,我只能给你黑马币,可以换技术分的,6黑马币=1技术分 ...

在哪里换啊???
回复 使用道具 举报
xiniuniu 发表于 2014-8-17 14:56
在哪里换啊???

设置-积分-兑换
回复 使用道具 举报
thank u very very much
回复 使用道具 举报
YuePr 中级黑马 2015-12-12 19:45:40
8#
厉害!!难得一见的技术好贴!!!!
回复 使用道具 举报
我正好想打印isa,没找到办法,就看见这个贴了,但是还是看不懂。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马