面试驱动技术合集(初中级iOS开发),关注仓库,及时获取更新 Interview-seriesgit
说到iOS,要么公司规模比较小,<=3人,不须要面试。github
其余的,大几率要让你刀枪棍棒十八般武艺都拿出来耍耍。面试
而其中,但凡敌军阵营中有iOSer的,又极大几率会考到 Runtime 的知识点。bash
如下,是一题 sunnyxx的一道 runtime 考题,给大伙练练手,若是掌握了,Runtime层面的初中级问题应该都不在话下~函数
//MNPerson
@interface MNPerson : NSObject
@property (nonatomic, copy)NSString *name;
- (void)print;
@end
@implementation MNPerson
- (void)print{
NSLog(@"self.name = %@",self.name);
}
@end
---------------------------------------------------
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
id cls = [MNPerson class];
void *obj = &cls;
[(__bridge id)obj print];
}
复制代码
问输出结果是啥,会不会崩溃。ui
最终结果:atom
self.name = <ViewController: 0x7fe667608ae0>
复制代码
what?spa
[MNPerson alloc]init]
??当前内存地址结构 - 与正常的[person print]
对比3d
调用print 方法,不须要关心有没有成员变量
_name
,因此能够理解为,cls == isa指针
print
函数问题2:为啥里面打印的是 ViewController
这就须要了解到iOS的内存分配相关知识
void test(){
int a = 4;
int b = 5;
int c = 6;
NSLog(@"a = %p,b = %p,c = %p",&a,&b,&c);
}
---------------------------
a = 0x7ffee87e9fdc,
b = 0x7ffee87e9fd8,
c = 0x7ffee87e9fd4
复制代码
OC方法的本质,实际上是函数调用, 底层就是调用 objc_msgSend() 函数发送消息。
- (void)viewDidLoad {
[super viewDidLoad];
NSString *test = @"666";
id cls = [MNPerson class];
void *obj = &cls;
[(__bridge id)obj print];
}
复制代码
以上述代码为例,三个变量 - test、cls、obj,都是局部变量,因此都在栈空间
栈空间是从高地址到低地址分配,因此test是最高地址,而obj是最低地址
MNPerson底层结构
struct MNPerson_IMPL{
Class isa;
NSString *_name;
}
- (void)print{
NSLog(@"self.name = %@",self->_name);
}
复制代码
_name
成员变量,实际上是经过self ->
去查找;[(__bridge id)obj print];
即经过 obj 开始找;_name
,是经过指针地址查找,找得MNPerson_IMPL
结构体MNPerson_IMPL
里面就两个变量,因此这里查找 _name
,就是经过 isa
的地址,跳过8个字节,找到 _name
而前面又说过,cls = isa,而_name 的地址 = isa往下偏移 8 个字节,因此上面的图能够转成
_name的本质,先找到 isa,而后跳过 isa 的八个字节,就找到 _name这个变量
因此上图输出
self.name = 666
复制代码
最先没有 test变量的时候呢
- (void)viewDidLoad {
[super viewDidLoad];
id cls = [MNPerson class];
void *obj = &cls;
[(__bridge id)obj print];
}
复制代码
底层 - objc_msgSendSuper
objc_msgSendSuper({ self, [ViewController class] },@selector(ViewDidLoad)),
等价于:
struct temp = {
self,
[ViewController class]
}
objc_msgSendSuper(temp, @selector(ViewDidLoad))
复制代码
因此等于有个局部变量 - 结构体 temp,
结构体的地址 = 他的第一个成员,这里的第一个成员是self
因此等价于 _name = self = 当前ViewController,因此最后输出
self.name = <ViewController: 0x7fc6e5f14970>
复制代码
**其实super的本质,不是 objc_msgSendSuper({self,[super class],@selector(xxx)}) **
而是
objc_msgSendSuper2(
{self,
[current class]//当前类
},
@selector(xxx)})
复制代码
函数内部逻辑,拿到第二个成员 - 当前类,经过superClass指针找到他的父类,从superClass开始搜索,最终结果是差很少的~
友情演出:小马哥MJ
题目来源: