ARC简化了手工维护资源的麻烦,熟练使用ARC也需要遵守一些规则。
以下是对__strong引用修饰符的一段测试代码
#import <Foundation/Foundation.h>
@interface ClassA: NSObject @end
@implementation ClassA
-(id) init
{
if (self = [super init])
{
NSLog(@"init %@", self);
}
return self;
}
-(void) dealloc
{
NSLog(@"dealloc %@", self);
//不再调用基类的dealloc,这也是个规则
}
@end
int main(int argc, const char * argv[])
{
NSLog(@"begin");
@autoreleasepool {
ClassA *obj0, *obj1, *obj2;
obj0 = [ClassA new];
NSLog(@"1 obj0=%@ obj1=%@ obj2=%@", obj0, obj1, obj2);
@autoreleasepool {
obj1 = [ClassA new];
NSLog(@"2 obj0=%@ obj1=%@ obj2=%@", obj0, obj1, obj2);
obj2 = nil;
NSLog(@"3 obj0=%@ obj1=%@ obj2=%@", obj0, obj1, obj2);
obj2 = obj0;
NSLog(@"4 obj0=%@ obj1=%@ obj2=%@", obj0, obj1, obj2);
obj0 = nil;
NSLog(@"5 obj0=%@ obj1=%@ obj2=%@", obj0, obj1, obj2);
obj1 = obj0;
NSLog(@"6 obj0=%@ obj1=%@ obj2=%@", obj0, obj1, obj2);
obj0 = obj2;
NSLog(@"7 obj0=%@ obj1=%@ obj2=%@", obj0, obj1, obj2);
}
obj2 = nil;
NSLog(@"8 obj0=%@ obj1=%@ obj2=%@", obj0, obj1, obj2);
}
NSLog(@"end");
return 0;
}
mac os下输出结果
2015-02-10 16:33:37.927 cpro[505:12653] begin
2015-02-10 16:33:37.929 cpro[505:12653] init <ClassA: 0x1003003a0>
2015-02-10 16:33:37.929 cpro[505:12653] 1 obj0=<ClassA: 0x1003003a0> obj1=(null) obj2=(null)
2015-02-10 16:33:37.929 cpro[505:12653] init <ClassA: 0x1001003e0>
2015-02-10 16:33:37.929 cpro[505:12653] 2 obj0=<ClassA: 0x1003003a0> obj1=<ClassA: 0x1001003e0> obj2=(null)
2015-02-10 16:33:37.929 cpro[505:12653] 3 obj0=<ClassA: 0x1003003a0> obj1=<ClassA: 0x1001003e0> obj2=(null)
2015-02-10 16:33:37.929 cpro[505:12653] 4 obj0=<ClassA: 0x1003003a0> obj1=<ClassA: 0x1001003e0> obj2=<ClassA: 0x1003003a0>
2015-02-10 16:33:37.929 cpro[505:12653] 5 obj0=(null) obj1=<ClassA: 0x1001003e0> obj2=<ClassA: 0x1003003a0>
2015-02-10 16:33:37.930 cpro[505:12653] dealloc <ClassA: 0x1001003e0>
2015-02-10 16:33:37.930 cpro[505:12653] 6 obj0=(null) obj1=(null) obj2=<ClassA: 0x1003003a0>
2015-02-10 16:33:37.930 cpro[505:12653] 7 obj0=<ClassA: 0x1003003a0> obj1=(null) obj2=<ClassA: 0x1003003a0>
2015-02-10 16:33:37.930 cpro[505:12653] 8 obj0=<ClassA: 0x1003003a0> obj1=(null) obj2=(null)
2015-02-10 16:33:38.046 cpro[505:12653] dealloc <ClassA: 0x1003003a0>
2015-02-10 16:33:38.047 cpro[505:12653] end
无论怎样,创建和释放的次数是对称的。
可以看到,局部变量被初始化为nil;把对象设置为nil,会提前释放内存。