iOS中类、元类、isa详解
类相信大家都知道是什么,如果看过runtime的源码或者看过相关的文章对isa肯定也不陌生,不过元类(meta class)大家可能就比较陌生了。不过大家也不要担心,我会细细道来,让大家明白它到底是个什么东西。
先看一段大家非常熟悉的代码:
| 
 1 
 | 
Person *person = [[Person alloc] init]; | 
为什么Person类名就能调用到alloc方法吗?到底怎么找到了alloc的方法了呢?
1.首先,在相应操作的对象中的缓存方法列表中找调用的方法,如果找到,转向相应实现并执行。
2.如果没找到,在相应操作的对象中的方法列表中找调用的方法,如果找到,转向相应实现执行
3.如果没找到,去父类指针所指向的对象中执行1,2.
4.以此类推,如果一直到根类还没找到,转向拦截调用,走消息转发机制。
5.如果没有重写拦截调用的方法,程序报错。
上边是我从网上一篇文章摘录的查找alloc的方法的大体过程。如果是实例方法(声明以`-`开头)这个描述的换个过程还是可以的,不过如果是类方法(声明以`+`开头比如`alloc`方法)还是有所欠缺的!
元类
`元类`也是类,是描述`Class `类对象的类。
| 
 1 
 | 
Class aclass = [Person class]; | 
>一切皆对象。每一个对象都对应一个类。 `Person` 类就是`person`变量对象的类,换句话说就是`person`对象的isa指向`Person`对应的结构体的类;`aclass`也是对象,描述它的类就是元类,换句话说`aclass`对象的isa指向的就是`元类`。
**元类保存了类方法的列表**。当一个类方法被调用时,元类会首先查找它本身是否有该类方法的实现,如果没有则该元类会向它的父类查找该方法,直到一直找到继承链的头。(回答文章上边查找方法所欠缺的地方)

这张图是非常精髓的,直接诠释了元类和isa。大家可以一边阅读本文,一边回忆此图,多看几遍。
上边都是概念性质偏多,不知道大家理解的如何。现在看一个实例来具体介绍上边的内容。
代码示例
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
 | 
//  Created by FlyOceanFish on 2018/1/9.//  Copyright © 2018年 FlyOceanFish. All rights reserved.//#import #import @interface Person: NSObject@end@implementation Person+ (void)printStatic{}- (void)print{    NSLog(@"This object is %p.", self);    NSLog(@"Class is %@, and super is %@.", [self class], [self superclass]);    const char *name = object_getClassName(self);    Class metaClass = objc_getMetaClass(name);    NSLog(@"MetaClass is %p",metaClass);    Class currentClass = [self class];    for (int i = 1; i < 5; i++)    {        NSLog(@"Following the isa pointer %d times gives %p", i, currentClass);            unsigned int countMethod = 0;        NSLog(@"---------------**%d start**-----------------------",i);        Method * methods = class_copyMethodList(currentClass, &countMethod);        [self printMethod:countMethod methods:methods ];        NSLog(@"---------------**%d end**-----------------------",i);        currentClass = object_getClass(currentClass);    }    NSLog(@"NSObject's class is %p", [NSObject class]);    NSLog(@"NSObject's meta class is %p", object_getClass([NSObject class]));}- (void)printMethod:(int)count methods:(Method *) methods{    for (int j = 0; j < count; j++) {        Method method = methods[j];        SEL methodSEL = method_getName(method);        const char * selName = sel_getName(methodSEL);        if (methodSEL) {            NSLog(@"sel------%s", selName);        }    }}@end@interface Animal: NSObject@end@implementation Animal- (void)print{    NSLog(@"This object is %p.", self);    NSLog(@"Class is %@, and super is %@.", [self class], [self superclass]);    const char *name = object_getClassName(self);    Class metaClass = objc_getMetaClass(name);    NSLog(@"MetaClass is %p",metaClass);    Class currentClass = [self class];    for (int i = 1; i < 5; i++)    {        NSLog(@"Following the isa pointer %d times gives %p", i, currentClass);        currentClass = object_getClass(currentClass);    }    NSLog(@"NSObject's class is %p", [NSObject class]);    NSLog(@"NSObject's meta class is %p", object_getClass([NSObject class]));}@endint main(int argc, const char * argv[]) {    @autoreleasepool {        Person *person = [[Person alloc] init];        Class class = [Person class];        [person print];//        printf("--------------------------------");//        Animal *animal = [[Animal alloc] init];//        [animal print];    }    return 0;} | 
这个示例有两部分功能:
1. 大家只看`Person`的演示功能即可。
2. 观察Person和Animal两个对象的打印(打印方法名的可以注释掉,将main方法中的代码注释打开)
`Person`的演示功能(不打印方法名称)
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
 | 
This object is 0x100408400.Class is Person, and super is NSObject.MetaClass is 0x100001328Following the isa pointer 1 times gives 0x100001350Following the isa pointer 2 times gives 0x100001328Following the isa pointer 3 times gives 0x7fffb9a4f0f0Following the isa pointer 4 times gives 0x7fffb9a4f0f0NSObject's class is 0x7fffb9a4f140NSObject's meta class is 0x7fffb9a4f0f0 | 
我们来观察isa到达过的地址的值:
对象的地址是 0x100408400.
类的地址是 0x100001350.
元类的地址是 0x100001328.
根元类(NSObject的元类)的地址是 0x7fffb9a4f0f0.
对于本次打印我们可以做出以下结论(可以再去看一遍上边那张精髓的图):
对于3、4次打印相同,就是因为NSObject元类的类是它本身.
我们在实例化对象的时候,其实是创建了许多对象,这就是我们说的类簇。也对应了我们在用runtime创建类的时候`objc_allocateClassPair(xx,xx)`中是`ClassPair`而不是`bjc_allocateClass`
通过地址的大小也可以看出对象实例化先后,地址越小的越先实例化
很好的诠释了上边那张精髓图isa的指向
NSObject的两个地址都非常大(哈哈哈哈哈!为什么非常大啊??接下往下看)
`Person`的演示功能(打印方法名称)
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
 | 
Class is Person, and super is NSObject.MetaClass is 0x100002378Following the isa pointer 1 times gives 0x1000023a0---------------**1 start**----------------------- sel------printMethod:methods:sel------print---------------**1 end**-----------------------Following the isa pointer 2 times gives 0x100002378---------------**2 start**-----------------------sel------printStatic---------------**2 end**-----------------------Following the isa pointer 3 times gives 0x7fffb9a4f0f0 ---------------**3 start**----------------------- | 
我只把重要的复制出来了,`NSObject`的所有的方法名没有复制出来,在此处不是重要的。
此次打印结果的结论:
类方法(静态方法)是存储在元类中的
观察Person和Animal两个对象的打印
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
 | 
This object is 0x100508e70.Class is Person, and super is NSObject.MetaClass is 0x100001338Following the isa pointer 1 times gives 0x100001360Following the isa pointer 2 times gives 0x100001338Following the isa pointer 3 times gives 0x7fffb9a4f0f0Following the isa pointer 4 times gives 0x7fffb9a4f0f0NSObject's class is 0x7fffb9a4f140NSObject's meta class is 0x7fffb9a4f0f0--------------------------------This object is 0x100675ed0.Class is Animal, and super is NSObject.MetaClass is 0x100001388Following the isa pointer 1 times gives 0x1000013b0Following the isa pointer 2 times gives 0x100001388Following the isa pointer 3 times gives 0x7fffb9a4f0f0Following the isa pointer 4 times gives 0x7fffb9a4f0f0NSObject's class is 0x7fffb9a4f140NSObject's meta class is 0x7fffb9a4f0f0Program ended with exit code: 0 | 
此次打印的结论:
`Animal`相关打印的地址都比`Person`的大。再次诠释了栈是由大往小排列的。栈口在最小的地方
`Animal`和`Person`的`NSObject`的两个地址一样。(知道为什么大了吗?其实就是保证这两个地址足够大,以致于永远在栈中。这样整个程序中其实就是存在一个,有点像单例的意思)
iOS中类、元类、isa详解的更多相关文章
- iOS 视图控制器转场详解
		
iOS 视图控制器转场详解 前言的前言 唐巧前辈在微信公众号「iOSDevTips」以及其博客上推送了我的文章后,我的 Github 各项指标有了大幅度的增长,多谢唐巧前辈的推荐.有些人问我相关的问题 ...
 - iOS 开发之照片框架详解(2)
		
一. 概况 本文接着 iOS 开发之照片框架详解,侧重介绍在前文中简单介绍过的 PhotoKit 及其与 ALAssetLibrary 的差异,以及如何基于 PhotoKit 与 AlAssetLib ...
 - iOS中MVC等设计模式详解
		
iOS中MVC等设计模式详解 在iOS编程,利用设计模式可以大大提高你的开发效率,虽然在编写代码之初你需要花费较大时间把各种业务逻辑封装起来.(事实证明这是值得的!) 模型-视图-控制器(MVC)设计 ...
 - iOS 开发之照片框架详解之二 —— PhotoKit 详解(下)
		
本文链接:http://kayosite.com/ios-development-and-detail-of-photo-framework-part-three.html 这里接着前文<iOS ...
 - iOS 开发之照片框架详解之二 —— PhotoKit 详解(上)
		
转载自:http://kayosite.com/ios-development-and-detail-of-photo-framework-part-two.html 一. 概况 本文接着 iOS 开 ...
 - 《iOS 7 应用开发实战详解》
		
<iOS 7 应用开发实战详解> 基本信息 作者: 朱元波 管蕾 出版社:人民邮电出版社 ISBN:9787115343697 上架时间:2014-4-25 出版日期:2014 年5 ...
 - iOS百度地图简单使用详解
		
iOS百度地图简单使用详解 百度地图 iOS SDK是一套基于iOS 5.0及以上版本设备的应用程序接口,不仅提供展示地图的基本接口,还提供POI检索.路径规划.地图标注.离线地图.定位.周边雷达等丰 ...
 - 《手把手教你》系列基础篇(九十七)-java+ selenium自动化测试-框架设计篇-Selenium方法的二次封装和页面基类(详解教程)
		
1.简介 上一篇宏哥介绍了如何设计支持不同浏览器测试,宏哥的方法就是通过来切换配置文件设置的浏览器名称的值,来确定启动什么浏览器进行脚本测试.宏哥将这个叫做浏览器引擎类.这个类负责获取浏览器类型和启动 ...
 - iOS 证书与签名 解惑详解
		
iOS 证书与签名 解惑详解 分类: iPhone2012-06-06 19:57 9426人阅读 评论(1) 收藏 举报 iosxcodecryptographyappleiphone测试 目录 ...
 - iOS 6分享列表——UIActivityViewController详解
		
iOS 6分享列表——UIActivityViewController详解 2013-06-03 01:42:33 发表评论 在iOS 6之后提供了一个分享列表视图,它通过UIActivity ...
 
随机推荐
- linux每日命令(17):which命令
			
我们经常在linux要查找某个文件,但不知道放在哪里了,可以使用下面的一些命令来搜索: which 查看可执行文件的位置. whereis 查看文件的位置. locate 配合数据库查看文件位置. f ...
 - 不平衡学习 Learning from Imbalanced Data
			
问题: ICC警情数据分类不均,30+分类,最多的分类数据数量1w+条,只有10个类别数量超过1k,大部分分类数量少于100条. 解决办法: 下采样:通过非监督学习,找出每个分类中的异常点,减少数据. ...
 - [php] thinkphp基于Http类 下载文件
			
http://blog.csdn.net/u010081689/article/details/49360937
 - Android——RecycleView
			
RecycleView设置点击事件 http://blog.csdn.net/guxiao1201/article/details/40423361
 - WebMisCentral-Client 适配MySql数据库
			
由于本身WebMisCentral采用的是EF5.0,所以适配起来还是非常简单的,下面看操作: 1.ElegantWM.WebUI层中(或者ElegantWM.DAL)通过NUGET下载MySQL.D ...
 - [C#] 一款代码注释清理工具
			
[C#] 一款代码注释清理工具 在程序开发过程中,很多时候我们都会在代码中进行注释,以便大家更容易理解或能更直观明白某个类或方法是用来做什么的,我们就会用注释 就以C#为列子,注释符大致为'//' ...
 - Java知多少(68)面向字符的输出流
			
面向字符的输出流都是类 Writer 的子类,其类层次结构如图 10-5 所示. 图10-5 Writer的类层次结构图 表 10-3 列出了 Writer 的主要子类及说明. 表 10-3 Writ ...
 - Java知多少(72)文件的随机读写
			
Java.io 包提供了 RandomAccessFile 类用于随机文件的创建和访问.使用这个类,可以跳转到文件的任意位置读写数据.程序可以在随机文件中插入数据,而不会破坏该文件的其他数据.此外,程 ...
 - 每一个开发人员都应该有一款自己的App
			
[谋哥每天一干货] 这篇文章不是鸡汤,是谋哥自己的感悟了. 谋哥近期每日一干货,坚持每天写,才发现这个事情你要是能坚持一年超级难.365天无论刮风下雨.心情好或不好.生病或生气.每天 ...
 - Service 中的 onStart 和 onStartCommand
			
在自定义的service中,写了onStart和onStartCommand, public class HttpWebService extends Service { @Override publ ...