Automatic Reference Counting (ARC)是编译器自动管理Objective-C对象的一个功能,相对于不得不考虑retain和release操作来说,ARC让我们有更多的精力集中在我们应用内有趣的代码、object graphs和对象之间的关系上。
概要
ARC是用过来在编译的时候添加适当的代码来保证对象在有用的时候有效,没有了就不再有效了。从概念上讲,ARC通过调用合适的内存管理方法遵循着和 manual reference counting(MRC)同样的内存管理规则。
为了让编译器产生正确的代码,ARC严格规定了你可以调用的方法和怎样使用toll-free bridging。ARC引入了新的用于对象引用和属性声明的生命周期标识符。
ARC支持Xcode 4.2 for OS X v10.6 and v10.7 (64-bit applications) and for iOS 4 and iOS 5。弱引用不支持OS X v10.6 and iOS 4。
Xcode提供了一个工具用来把非ARC代码自动转换到ARC代码(例如移除retain和release的调用),解决的不能自动迁移的问题。这个工具会把工程中的所有文件都转换成ARC,在使用非ARC方便的情况下,你也可以选择某些文件使用ARC。
ARC概况
不用再记住什么时候该使用retain、release和autorelease了,ARC知道你的对象的使用周期然后在编译的时候加入了合适的内存管理代码。编译器也会为你生成合适的dealloc方法。如果你刚刚使用ARC,那么传统的Cocoa的命名规范在你管理MRC的代码的时候是非常重要的。
一个完整的正确的Person类的实现是这样的:
@interface Person : NSObject @property NSString *firstName; @property NSString *lastName; @property NSNumber *yearOfBirth; @property Person *spouse; @end @implementation Person @end
对象的属性默认是strong的。
使用ARC,你可能实现这样一个方法contrived :
- (void)contrived {
Person *aPerson = [[Person alloc] init];
[aPerson setFirstName:@"William"];
[aPerson setLastName:@"Dudney"];
[aPerson setYearOfBirth:[[NSNumber alloc] initWithInteger:2011]];
NSLog(@"aPerson: %@", aPerson);
}
ARC接管里内存管理,所以Person和NSNumber都不会造成内存泄露。
你也可以安全的实现一个Person的方法takeLastNameFrom:
- (void)takeLastNameFrom:(Person *)person {
NSString *oldLastname = [self lastName];
[self setLastName:[person lastName]];
NSLog(@"Lastname changed from %@ to %@", oldLastname, [self lastName]);
}
ARC能够确保 oldLastName 在NSLog之前不被释放。
ARC强制的新规则
ARC提出了一些新的别的编译器没有的新规则。这些规定是为了能够提供一个完整的可靠的内存管理模型。在一些情况能够很简单的提升性能,在一些情况下能够简化代码或者让你不用处理内存管理。如果你违背这些规则,在编译的时候就会出错,而不是在运行的时候产生错误。
- 你不能显示的调用dealloc,实现或者调用retain、release、retianCount或者autorealease。
@selector(retain) , @selector(release)等等- 你不能使用
NSAllocateObject 和NSDeallocateObject
- 在C结构体中不能使用对象指针。
- 不能随便的转换id和void*
- 你不能是用NSAutoreleasePool
- 你不能是用内存zones
- 不能提供以new开头的获取方法,这意味着你不能添加一个以new开头的属性,而不自己添加get方法。
// Won't work:
@property NSString *newTitle;
// Works:
@property (getter=theNewTitle) NSString *newTitle;
ARC提出了新的生命周期标识符
Property属性
// The following declaration is a synonym for: @property(retain) MyClass *myObject; @property(strong) MyClass *myObject; // The following declaration is similar to "@property(assign) MyClass *myObject;" // except that if the MyClass instance is deallocated, // the property value is set to nil instead of remaining as a dangling pointer. @property(weak) MyClass *myObject;在ARC下,strong是默认的对象类型。
变量标识符
__strong __weak __unsafe_unretained __autoreleasing
- __strong是默认的,一个对象只要有__strong类型指针指向它,它就有效。
- __weak声明了一个引用并不持有该对象。当没有强引用指向弱引用指向的对象的时候,弱引用被赋值为nil。
- __unsafe__unretain声明了一个不持有对象的引用。当没有强引用指向该对象的时候,该引用不会被赋值为nil,所以当一个该引用指向的对象被回收的时候,该引用是危险的。
- __autorelease是用来声明通过id*传递并返回autorelease的参数的。
ClassName * qualifier variableName;例如:
MyClass * __weak myWeakReference; MyClass * __unsafe_unretained myUnsafeReference;其他变种写法在技术上是不正确的,当时是被编译器允许,想要了解更过可以看这里: http://cdecl.org/
NSString * __weak string = [[NSString alloc] initWithFormat:@"First Name: %@", [self firstName]]; NSLog(@"string: %@", string);虽然string是在初始化赋值之后使用的,但是在赋值的时候没有强引用指向string,因此它立刻就会被释放。NSLog语句会输出一个null值(在此例子中编译器会给出警告)。
NSError *error;
BOOL OK = [myObject performOperationWithError:&error];
if (!OK) {
// Report the error.
// ...
然而这个声明是错误的而且是隐式的。NSError * __strong e;其实这个方法的声明如下:
-(BOOL)performOperationWithError:(NSError * __autoreleasing *)error;
NSError * __strong error;
NSError * __autoreleasing tmp = error;
BOOL OK = [myObject performOperationWithError:&tmp];
error = tmp;
if (!OK) {
// Report the error.
// ...
使用生命周期标识符避免循环引用
MyViewController *myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler = ^(NSInteger result) {
[myController dismissViewControllerAnimated:YES completion:nil];
};
[self presentViewController:myController animated:YES completion:^{
[myController release];
}];
正像是描述的一样,你可以使用__block标识符,在completion handler内设置myController为nil:MyViewController * __block myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler = ^(NSInteger result) {
[myController dismissViewControllerAnimated:YES completion:nil];
myController = nil;
};
另外,你可以使用一个临时的__weak变量。下面的例子声明了一个简单是实现:MyViewController *myController = [[MyViewController alloc] init…];
// ...
MyViewController * __weak weakMyViewController = myController;
myController.completionHandler = ^(NSInteger result) {
[weakMyViewController dismissViewControllerAnimated:YES completion:nil];
};
没有了循环引用,但是你应该这样用:MyViewController *myController = [[MyViewController alloc] init…];
// ...
MyViewController * __weak weakMyController = myController;
myController.completionHandler = ^(NSInteger result) {
MyViewController *strongMyController = weakMyController;
if (strongMyController) {
// ...
[strongMyController dismissViewControllerAnimated:YES completion:nil];
// ...
}
else {
// Probably nothing...
}
};
在一些情况下如果__weak是不兼容的你可能使用__unsafe__unretained。然而对于循环引用这个可能变得不切实际,因为是非常难得或者不可能验证__unsafe__unretained指针是有效的和指向了同样有问题的对象。ARC使用了新的语句来管理Autorelease Pools
@autoreleasepool {
// Code, such as a loop that creates a large number of temporary objects.
}
这个简单的结构可以允许编译器来推断引用计数状态。在入口处,一个autorelease pool被放进栈。在退出的地方(break,return,goto,fall-through等等)autorelease pool被弹出栈。为了兼容已经存在的代码,如果由于异常退出,autorelease pool是不会被弹出栈的。Patterns for Managing Outlets Become Consistent Across Platforms(管理Outlets)
栈变量初始化为nil
- (void)myMethod {
NSString *name;
NSLog(@"name: %@", name);
}
NSLog语句将会输出null而不是crashing。