preface

When exploring OC objects, we need to use Apple objC open-source source code for targeted exploration. The following is the pit I stepped in the process of objC source code compilation, and the source code can be compiled.

Build objc824 source address: www.jianshu.com/p/f830d4cbc…

Pointers and memory to OC objects

LGPerson *p1 = [LGPerson alloc];
LGPerson *p2 = [p1 init];
LGPerson *p3 = [p1 init];

NSLog(@"%@-%p-%p",p1,p1,&p1);
NSLog(@"%@-%p-%p",p2,p2,&p2);
NSLog(@"%@-%p-%p",p3,p3,&p3);
Copy the code

Print the picture:

It is found that p1, P2, P3 prints are the same, while &P1, & P2, & P3 prints are different. Yes.

The reason:

  • Alloc is a method of opening up memory, and when LGPerson calls alloc and assigns it to P1, it’s like assigning p1 to the memory address that alloc assigned to. P1 is assigned to P2 and P3 after init, and the initialized memory is still the same, so P1, P2, The p3 print is the same.

  • The memory addresses of &p1, &P2, &p3 are in the stack space, so printing finds that their memory addresses are different and consecutive, and they point to the same memory.

With a graph:

Compiler optimization

int lgSum(int a, int b){
    return a+b;
}

int main(int argc, char * argv[]) {
    int a = 10;
    int b = 20;
    int c = lgSum(a, b);
    NSLog(@"View compiler optimizations :%d",c);
    return 0;
}
Copy the code

This code is viewed in assembly:

As you can see, this is a lot of assembly generated by just a few lines of code, but it is important to note that iOS does not have compiler optimization by default in Debug mode, so you need to set it manually:

After setting up, recompile, breakpoint to view assembly code:

There is not as much assembly code, 10 and 20 are missing, method calls are missing, and the compiler simply gives the result -> 30, which is the result of compiler optimization. Results.