结论:
alloc负责分配内存和创建对象对应的isa指针;
init只是返回alloc生成的对象。
所以alloc后,多次调用init,返回的对象是同一个!
代码如下:
1 // 2 // main.m 3 // alloc.initTest 4 // 5 // Created by LongMa on 2019/5/30. 6 // Copyright © 2019. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 11 int main(int argc, const char * argv[]) { 12 @autoreleasepool {15 16 NSObject *obj1 = [NSObject alloc]; 17 NSLog(@"%p",obj1); 18 19 NSObject *obj2 = [obj1 init]; 20 NSObject *obj3 = [obj1 init]; 21 NSLog(@"%p",obj2); 22 NSLog(@"%p",obj3); 23 } 24 return 0; 25 }
运行结果:
2019-05-30 09:35:37.019843+0800 alloc.initTest[65183:12003258] 0x10065d810
2019-05-30 09:35:37.019864+0800 alloc.initTest[65183:12003258] 0x10065d810
2019-05-30 09:35:37.019874+0800 alloc.initTest[65183:12003258] 0x10065d810
Program ended with exit code: 0
启发文章参考:http://www.cocoachina.com/ios/20190527/27009.html