The source code used for this article is objC4-818

There are two common ways to create objects:

UIView *v = [[UIView alloc] init];
UIView *v = [UIView new];
Copy the code

What’s the difference between these two? We’ll find the alloc method and the implementation of the new method in the Source file (Source/ nsobject.mm) and let’s look at new

+ (id)new {
    return [callAlloc(self, false/*checkNil*/) init];
}
Copy the code

The new method calls callAlloc, init

CallAlloc 2557 - (id)init {return _objc_rootInit(self); }Copy the code

So alloc and init

+ (id)alloc {
    return _objc_rootAlloc(self);
}
- (id)init {
    return _objc_rootInit(self);
}
Copy the code

Init with this method in the alloc method, and then call the callAlloc method as well

// Base class implementation of +alloc. cls is not nil.
// Calls [cls allocWithZone:nil].
id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
Copy the code

By comparison, callAlloc is called, but callAlloc? I passed two arguments to new and I passed three arguments to alloc, which is this bool allocWithZone=false

// Call [CLS alloc] or [CLS allocWithZone:nil], with appropriate // shortcutting optimizations. static ALWAYS_INLINE id callAlloc(Class cls, bool checkNil, bool allocWithZone=false) { #if __OBJC2__ if (slowpath(checkNil && ! cls)) return nil; 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)); }Copy the code

So alloc goes allocWithZone, and new goes alloc

The difference between

  1. allocUsed when allocating memoryallocWithZone, it allocates the associated object to an adjacent area when allocating memory to the object, so as to consume less memory when calling, and improve the processing speed of the program
  2. alloc initYou can start againinitA little bit more customization,newIf it’s fixed, it’s dead

End