NSObject 调用 alloc 与 new 方法的区别
在实际开发中,我们有时会用到new
去创建一个对象,有时也会用到alloc
创建一个对象,那么他们两者之间到底有什么样的区别?
NSObject *obj1 = [NSObject alloc];
NSObject *obj2 = [[NSOBject alloc] init];
NSObject *obj3 = [NSObject new];
通过 runtime 源码分析,我们发现 :
[NSObject alloc]
底层并没有调用+ alloc
方法,而是调用了objc_alloc
方法,然后在方法内部调用callAlloc
方法,具体代码如下:
objc_alloc(Class cls)
{
return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
}
[[NSObject alloc] init]
底层会调用objc_alloc_init
方法,然后在方法内部调用callAlloc
方法,具体代码如下:
objc_alloc_init(Class cls)
{
return [callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/) init];
}
[NSObject new]
底层并没有调用+ new
方法,会调用objc_opt_new
方法,然后内部再调用callAlloc
,具体代码如下:
objc_opt_new(Class cls)
{
#if __OBJC2__
/**
#define fastpath(x) (__builtin_expect(bool(x), 1))
fastpath(x)告诉编译器x的值一般不为0,希望编译器进行优化
slowpath(x)告诉编译器x很可能为0,希望编译器进行优化
__builtin_expect((x),1)表示 x 的值为真的可能性更大;
__builtin_expect((x),0)表示 x 的值为假的可能性更大。
*/
if (fastpath(cls && !cls->ISA()->hasCustomCore())) {
return [callAlloc(cls, false/*checkNil*/) init];
}
#endif
return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(new));
}
callAlloc
内部方法的是实现:
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__
if (slowpath(checkNil && !cls)) return nil;
/**
hasCustomAllocWithZone——这里表示有没有alloc / allocWithZone的实现
只有不是继承NSObject/NSProxy的类才为true
*/
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
return _objc_rootAllocWithZone(cls, nil);
}
#endif
// No shortcuts available.
if (allocWithZone) {
return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
}
return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}
因此可以看出,[NSObject new]
相对于[NSObject alloc]
,最终都是调用了callAlloc
方法,只不过是[NSObject new]
隐式的调用了init
方法。
顺道看下init
方法的实现:
- (id)init {
return _objc_rootInit(self);
}
_objc_rootInit(id obj)
{
return obj;
}
可以看出init
其实什么都没做,只是把调用者返可回来。
转载自:https://juejin.cn/post/6979781972461617159