iOS alloc & init explore

1.alloc explore

Create a NSObject objects LGPerson

    LGPerson * p1 = [LGPerson alloc];

    LGPerson *p2 = [p1 init];

    LGPerson *p3 = [p1 init];

    LGNSLog(@"%@ - %p",p1,&p1);

    LGNSLog(@"%@ - %p",p1,&p2);

    LGNSLog(@"%@ - %p",p1,&p3);

 

Console printout:

<LGPerson: 0x600002208560> - 0x7ffee9a44118

<LGPerson: 0x600002208560> - 0x7ffee9a44110

<LGPerson: 0x600002208560> - 0x7ffee9a44108

Phenomenon: you can see three objects is printed with a
p1, p2, p3 pointer addresses are different, but they are pointing to the same piece of memory address

 

2.alloc is how to create? Concrete realization of the principle of inquiry

There are three ways to find

(1) a breakpoint 

    By control + in found objec_alloc

 

(2) by the following symbolic break point, if the methods known in advance, the direct

objc_alloc, or directly at the breakpoint alloc

 

 (3) by way of the assembler  

libobjc.A.dylib`objc_alloc:

 

 

 

 

 

3. through source code analysis process

Look Source  Download + configuration

Get the source code, global search alloc {, can be found alloc method, then enter

_objc_rootAlloc method, step by step.

As can be seen by the source code analysis process

 

 

 

 As can be seen from the above source alloc method opens up memory, a pointer to 8 bytes, there is provided in the outer A binary calculation here

    // (x + WORD_MASK)  >> 3 << 3

0000 1111 >> 3          0000 0001

0000 0001<<3           0000 1000  //8

对象需要内存空间  WORD_MASK 8的倍数 8字节对齐 同时if (size < 16) size = 16; 满足内存空间最小为16bytes

内存对齐:让CPU读取更加方便,用空间来换取时间

假设我们的内存快 字节方式补齐 如同4,5,6,7,8 读取就不方便

 

 

4.探索init,new方法

- (id)init {

    return _objc_rootInit(self);

}

 

id

_objc_rootInit(id obj)

{

    // In practice, it will be hard to rely on this function.

    // Many classes do not properly chain -init calls.

    return obj;

}

返回的就是alloc出来的obj。

init没做任何操作,一般在这里是工厂方式来重写方法,自定义,我们经常会这样写代码

- (instancetype)init{

    self = [super init];

    if (self) {

        

    }

    return self;

}

//

[super init] 重写父类的方法 防止覆盖父类的方法

self =  [super init]  

= 是确认继承父类 可以延伸自己的方法

if(self)做判断处理 防止父类在init的时候return nil 

做一个安全的处理 不然子类的实现就没有意义了

 

通过源码,看出new就是callAlloc+init的组合实现

+ (id)new {

    return [callAlloc(self, false/*checkNil*/) init];

}

 



Guess you like

Origin www.cnblogs.com/cui-cui/p/12057794.html