ARC
ARC是默认开启的。
在工程文件中的Build Settings中搜索reference。可以找到Objective-C Automatic Reference Count。默认为YES。设置为No则关闭。
void arcDemo(){
BLNPoint *p1 = [[BLNPoint alloc]init];
BLNRectangle *rect = [[BLNRectangle alloc]init];
// --------------- 引用计数 retain +1操作
BLNPoint *p2 = p1; // 赋值操作,增加了指向内容的指针 r(2)
rect.center = p1; // 赋值操作 r(3)
draw(p1); // 在执行完毕之后会自动-1 r(4) r(3)
array=[[NSMutableArray alloc]initWithCapacity:10];
[array addObject:p1]; r(4)
// --------------- 引用计数 release -1操作
p1 = nil; // r(3)
p2 = nil; // r(2)
rect.center = nil; // r(1)
[array removeObjectAtIndex:0]; // 把对象从集合中删除 r(0)
NSLog(@"continue......");
}
内存图
自动释放池
// 提前使用autoreleasepool释放内容,这也是一种嵌套使用的情况。
void poolDemo(){
@autoreleasepool {
for (int i = 0; i < 10; i++) {
__unused BLNRectangle *rect = [[BLNRectangle alloc]init];
}
}
}