iOS - 类的结构分析

内存偏移

以数组为例:

int a[4] = {1,2,3,4};
int *b = a;
NSLog(@"%p - %p - %p - %p",&a,&a[0],&a[1],&a[2]);
NSLog(@"%p - %p - %p",b,b+1,b+2);

打印结果:

0x7ffeefbff520 - 0x7ffeefbff520 - 0x7ffeefbff524 - 0x7ffeefbff528
0x7ffeefbff520 - 0x7ffeefbff524 - 0x7ffeefbff528

由上面结果可知:
1.由&a与&a[0]的打印结果相同可知,数组的首地址存着数组的第一个元素;
2.int占用4个字节,由打印b的指针可以看出,0x7ffeefbff520-> 0x7ffeefbff524地址偏移4个字节,通过对地址的偏移,我们一样可以找到数组a中的元素;

通过lldb测试由b拿到数组a中的元素:
(lldb) po *b
1
(lldb) po *(b+1)
2
(lldb) po *(b+2)
3

小结:我们可以通过地址偏移拿到自己需要的相应元素.

类的结构分析

首先我们来看一下类的结构是什么样的:

struct objc_class : objc_object {
    Class ISA;//8字节
    Class superclass;//结构体指针8字节
    cache_t cache;             // formerly cache pointer and vtable
    class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags
    class_rw_t *data() { 
        return bits.data();
    }
/**此处省略代码*/
}

typedef struct objc_class *Class;

由上面内存偏移的分析可知,如果我们要拿到class_data_bits_t bits,只需要知道我们需要对首地址便宜多少,便能拿到, Class定义为结构体,我们可以知道ISA,superclass各占8个字节, class_data_bits_t又占多少字节呢?

cache_t
struct cache_t {
    struct bucket_t *_buckets;//结构体8个字节
    mask_t _mask;//typedef uint32_t mask_t; 由此可知mask_t占用4个字节
    mask_t _occupied;//4个字节

public://方法不占内存
    struct bucket_t *buckets();
    mask_t mask();
    mask_t occupied();
    void incrementOccupied();
    void setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask);
    void initializeToEmpty();

    mask_t capacity();
    bool isConstantEmptyCache();
    bool canBeFreed();

    static size_t bytesForCapacity(uint32_t cap);
    static struct bucket_t * endMarker(struct bucket_t *b, uint32_t cap);

    void expand();
    void reallocate(mask_t oldCapacity, mask_t newCapacity);
    struct bucket_t * find(cache_key_t key, id receiver);

    static void bad_cache(id receiver, SEL sel, Class isa) __attribute__((noreturn));
};

由注释我们可以看出cache_t所占的字节说为16个字节,因此我们要拿到bits只需将首地址偏移8 + 8 +16 = 32字节便可得到;

class_rw_t结构
struct class_rw_t {
    // Be warned that Symbolication knows the layout of this structure.
    uint32_t flags;
    uint32_t version;

    const class_ro_t *ro;

    method_array_t methods;//方法
    property_array_t properties;//属性
    protocol_array_t protocols;//协议

    /**省略*/
};

通过class_rw_t结构可以看出来类的方法,属性,协议都在这里面;

那么我们就通过栗子来进行验证:

创建一个student的类:

@interface Student : NSObject{
    NSString *hobby;
}

@property (nonatomic, copy) NSString *name;

- (void)study;
+ (void)play;

@end
Student *student = [Student alloc];
Class sClass     = object_getClass(student);
NSLog(@"%@ - %p",student,sClass);

通过打断点用lldb进行调试:

(lldb) x/4gx sClass
0x1000025d8: 0x001d8001000025b1 0x0000000100b38140
0x1000025e8: 0x00000001003db260 0x0000000000000000
(lldb) p (class_data_bits_t *)0x1000025f8//由上面分析可知data存在首地址偏移32个字节的内存中,可计算出该地址,将其强转成class_data_bits_t类型
(class_data_bits_t *) $1 = 0x00000001000025f8
(lldb) p $1->data()
(class_rw_t *) $2 = 0x0000000100f3ec30
(lldb) p *$2
(class_rw_t) $3 = {
  flags = 2148139008
  version = 0
  ro = 0x00000001000024c8
  methods = {
    list_array_tt<method_t, method_list_t> = {
       = {
        list = 0x0000000100002400
        arrayAndFlag = 4294976512
      }
    }
  }
  properties = {
    list_array_tt<property_t, property_list_t> = {
       = {
        list = 0x00000001000024b0
        arrayAndFlag = 4294976688
      }
    }
  }
  protocols = {
    list_array_tt<unsigned long, protocol_list_t> = {
       = {
        list = 0x0000000000000000
        arrayAndFlag = 0
      }
    }
  }
  firstSubclass = nil
  nextSiblingClass = LGPerson
  demangledName = 0x0000000000000000
}
(lldb) p $3.properties
(property_array_t) $4 = {
  list_array_tt<property_t, property_list_t> = {
     = {
      list = 0x00000001000024b0
      arrayAndFlag = 4294976688
    }
  }
}
(lldb) p $4.list
(property_list_t *) $5 = 0x00000001000024b0
(lldb) p $5->first//由对property_list_t继承结构分析可知$5存在该字段
(property_t) $6 = (name = "name", attributes = "T@\"NSString\",C,N,V_name")
//property_list_t结构
struct property_list_t : entsize_list_tt<property_t, property_list_t, 0> {
};
struct entsize_list_tt {
    uint32_t entsizeAndFlags;
    uint32_t count;
    Element first;
}

通过答应我们确实在properties中找到了name属性,但却没找到hobby属性;
结合class_rw_t的结构,我们尝试从ro寻找:

(lldb) p $2->ro
(const class_ro_t *) $7 = 0x00000001000024c8
(lldb) p *$7
(const class_ro_t) $8 = {
  flags = 388
  instanceStart = 8
  instanceSize = 24
  reserved = 0
  ivarLayout = 0x0000000100001f80 "\x02"
  name = 0x0000000100001f82 "Student"
  baseMethodList = 0x0000000100002400
  baseProtocols = 0x0000000000000000
  ivars = 0x0000000100002468
  weakIvarLayout = 0x0000000000000000
  baseProperties = 0x00000001000024b0
}
(lldb) p $8.baseProperties
(property_list_t *const) $9 = 0x00000001000024b0
(lldb) p *$9
(property_list_t) $10 = {
  entsize_list_tt<property_t, property_list_t, 0> = {
    entsizeAndFlags = 16
    count = 1
    first = (name = "name", attributes = "T@\"NSString\",C,N,V_name")
  }
}
(lldb) p $10.get(0)
(property_t) $13 = (name = "name", attributes = "T@\"NSString\",C,N,V_name")

由上面打印结果可知: baseProperties存储着name属性,但hobby依旧没看到,我们尝试答应一下ivars发现:

(lldb) p $8.ivars
(const ivar_list_t *const) $11 = 0x0000000100002468
(lldb) p *$11
(const ivar_list_t) $12 = {
  entsize_list_tt<ivar_t, ivar_list_t, 0> = {
    entsizeAndFlags = 32
    count = 2
    first = {
      offset = 0x0000000100002550
      name = 0x0000000100001e14 "hobby"
      type = 0x0000000100001fa5 "@\"NSString\""
      alignment_raw = 3
      size = 8
    }
  }
}

(lldb) p $12.get(1)
(ivar_t) $14 = {
  offset = 0x0000000100002558
  name = 0x0000000100001e3d "_name"
  type = 0x0000000100001fa5 "@\"NSString\""
  alignment_raw = 3
  size = 8
}
(lldb) p $12.get(0)
(ivar_t) $15 = {
  offset = 0x0000000100002550
  name = 0x0000000100001e14 "hobby"
  type = 0x0000000100001fa5 "@\"NSString\""
  alignment_raw = 3
  size = 8
}

通过打印ivars我们找到了hobby,并且发现其count = 2;我们通过打印get方法可得到其存储了"name"和"hobby";
由此可知: 属性在底层会生成一个带下划线"
"的成员变量,也就是上面的_name成员变量
变量我们找到了,那方法又存储在哪呢?通过打印我们继续寻找:

(lldb) p $8.baseMethodList
(method_list_t *const) $16 = 0x0000000100002400
(lldb) p *$16
(method_list_t) $17 = {
  entsize_list_tt<method_t, method_list_t, 3> = {
    entsizeAndFlags = 26
    count = 4//存了四个方法
    first = {
      name = "study"
      types = 0x0000000100001f8a "v16@0:8"
      imp = 0x0000000100001b40 (LGTest`-[Student study] at Student.m:12)
    }
  }
}

通过打印我们发现baseMethodList中存了4个方法,那么我们就一一看看存了哪些方法:

(lldb) p $17.get(0)
(method_t) $18 = {
  name = "study"//study方法
  types = 0x0000000100001f8a "v16@0:8"
  imp = 0x0000000100001b40 (LGTest`-[Student study] at Student.m:12)
}
(lldb) p $17.get(1)
(method_t) $19 = {
  name = ".cxx_destruct"//c++的方法
  types = 0x0000000100001f8a "v16@0:8"
  imp = 0x0000000100001c10 (LGTest`-[Student .cxx_destruct] at Student.m:10)
}
(lldb) p $17.get(2)
(method_t) $20 = {
  name = "name"//name的get方法
  types = 0x0000000100001f92 "@16@0:8"
  imp = 0x0000000100001ba0 (LGTest`-[Student name] at Student.h:16)
}
(lldb) p $17.get(3)
(method_t) $21 = {
  name = "setName:"//name的set的方法
  types = 0x0000000100001f9a "v24@0:8@16"
  imp = 0x0000000100001bd0 (LGTest`-[Student setName:] at Student.h:16)
}

通过打印我们找了实例方法study,但是类方法play哪去了呢?猜想:类方法会不会存在元类中呢?

验证过程
(lldb) x/4gx sClass
0x1000025d8: 0x001d8001000025b1 0x0000000100b38140
0x1000025e8: 0x00000001003db260 0x0000000000000000
(lldb) p/x 0x001d8001000025b1 & 0x00007ffffffffff8
(long) $1 = 0x00000001000025b0//元类的地址
(lldb) x/4gx 0x00000001000025b0
0x1000025b0: 0x001d800100b380f1 0x0000000100b380f0
0x1000025c0: 0x00000001022175c0 0x0000000100000003
(lldb) p (class_data_bits_t *)0x1000025d0
(class_data_bits_t *) $2 = 0x00000001000025d0
(lldb) p $2->data()
(class_rw_t *) $3 = 0x0000000102217540
(lldb) p $3->ro
(const class_ro_t *) $4 = 0x00000001000023b8
(lldb) p *$4
(const class_ro_t) $5 = {
  flags = 389
  instanceStart = 40
  instanceSize = 40
  reserved = 0
  ivarLayout = 0x0000000000000000
  name = 0x0000000100001f82 "Student"
  baseMethodList = 0x0000000100002398
  baseProtocols = 0x0000000000000000
  ivars = 0x0000000000000000
  weakIvarLayout = 0x0000000000000000
  baseProperties = 0x0000000000000000
}
(lldb) p $5.baseMethodList
(method_list_t *const) $6 = 0x0000000100002398
(lldb) p *$6
(method_list_t) $7 = {
  entsize_list_tt<method_t, method_list_t, 3> = {
    entsizeAndFlags = 26
    count = 1
    first = {
      name = "play"
      types = 0x0000000100001f8a "v16@0:8"
      imp = 0x0000000100001b70 (LGTest`+[Student play] at Student.m:16)
    }
  }
}

通过对元类的方法的查找我们找到了play方法,同时也证明了类方法存在于元类中.

总结

1.类的属性和成员变量都存放在类的class_rw_t结构体中
2.属性的定义,还伴随着成员变量以及其getter和setter的自动生成
3.类的类方法,则以实例方法的形式,存放在元类中

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355