iPhone之IOS5内存管理(ARC技术概述)
ARC(Automatic Reference Counting )技术概述
此文章由Tom翻译,首发于csdn的blog,任何人都可以转发,但是请保留原始链接和翻译者得名字。多谢!
Automatic Reference Counting (ARC) 是一个编译期的技术,利用此技术可以简化Objective-C编程在内存管理方面的工作量。
这里我把此技术翻译为自动内存计数器管理技术,下图是使用和不使用此技术的Objective-C代码的区别。
ARC技术是随着XCode4.2一起发布的,在缺省工程模板中,你可以指定你的工程是否支持ARC技术,如果你不指定工程支持ARC技术,在代码中你必须使用管理内存的代码来管理内存。
概述
自动计数(ARC)是一个编译期间工作的能够帮你管理内存的技术,通过它,程序人员可以不需要在内存的retain,释放等方面花费精力。
ARC在编译期间为每个Objective-C指针变量添加合适的retain, release, autorelease等函数,保存每个变量的生存周期控制在合理的范围内,以期实现代码上的自动内存管理。
In order for the compiler to generate correct code, ARC imposes some restrictions on the methods you can use, and on how you use toll-free bridging (see “Toll-Free Bridged Types”); ARC also introduces new lifetime qualifiers for object references and declared properties.
你可以使用编译标记-fobjc-arc来让你的工程支持ARC。ARC在Xcode4.2中引入,在Mac OS X v10.6,v10.7 (64位应用),iOS 4,iOS 5中支持,Xcode4.1中不支持这个技术.
如果你现在的工程不支持ARC技术,你可以通过一个自动转换工具来转换你的工程(工具在Edit->Convert menu),这个工具会自动所有工程中手动管理内存的点转换成合适自动方式的(比如移除retain, release等)。这个工具会转换工程中所有的文件。当然你可以转换单个文件。
ARC提供自动内存管理的功能
ARC使得你不需要再思考何时使用retain,release,autorelease这样的函数来管理内存,它提供了自动评估内存生存期的功能,并且在编译期间自动加入合适的管理内存的方法。编译器也会自动生成dealloc函数。一般情况下,通过ARC技术,你可以不顾传统方式的内存管理方式,但是深入了解传统的内存管理是十分有必要的。
下面是一个person类的一个声明和实现,它使用了ARC技术。
@interface Person : NSObject |
@property (nonatomic, strong) NSString *firstName; |
@property (nonatomic, strong) NSString *lastName; |
@property (nonatomic, strong) NSNumber *yearOfBirth; |
@property (nonatomic, strong) Person *spouse; |
@end |
@implementation Person |
@synthesize firstName, lastName, yearOfBirth, spouse; |
@end |
(有关strong的帮助,请参考 “ARC Introduces New Lifetime Qualifiers.”)
使用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管理内存,所以这里你不用担心aPerson和NSNumber的临时变量会造成内存泄漏。
你还可以象下面的方式来实现Person类中的takeLastNameFrom:方法,
- (void)takeLastNameFrom:(Person *)person { |
NSString *oldLastname = [self lastName]; |
[self setLastName:[person lastName]]; |
NSLog(@"Lastname changed from %@ to %@", oldLastname, [self lastName]); |
} |
ARC可以保证在NSLog调用的时候,oldLastname还存在于内存中。
ARC中的新规则
为了ARC能顺利工作,特增加如下规则,这些规则可能是为了更健壮的内存管理,也有可能为了更好的使用体验,也有可能是简化代码的编写,不论如何,请不要违反下面的规则,如果违反,将会得到一个编译期错误。
下面的这些函数:
dealloc,
retain
,release
,retainCount
,autorelease。禁止任何形式调用和实现(dealloc可能会被实现),包括使用
@selector(retain)
,@selector(release)
等的隐含调用。你可能会实现一个和内存管理没有关系的dealloc,譬如只是为了调用
[systemClassInstance setDelegate:nil]
,但是请不要调用[super dealloc]
,因为编译器会自动处理这些事情。你不可以使用
NSAllocateObject
或者
NSDeallocateObject
.使用alloc申请一块内存后,其他的都可以交给运行期的自动管理了。
- 不能在C语言中的结构中使用Objective-c中的类的指针。
请使用类类管理数据。
不能使用NSAutoreleasePool
.作为替代,@autoreleasepool被引入,你可以使用这个效率更高的关键词。
不能使用memory zones.
NSZone不再需要
—本来这个类已经被现代Objective-c废弃。
ARC在函数和便利变量命名上也有一些新的规定
禁止以new开头的属性变量命名。
ARC Introduces New Lifetime Qualifiers
ARC introduces several new lifetime qualifiers for objects, and zeroing weak references. A weak reference does not extend the lifetime of the object it points to. A zeroing weak reference automatically becomes nil
if the object it points to is deallocated.
You should take advantage of these qualifiers to manage the object graphs in your program. In particular, ARC does not guard against strong reference cycles (previously known as retain cycles—see “Practical Memory Management”). Judicious use of weak relationships will help to ensure you don’t create cycles.
属性变量修饰符
weak和strong两个修饰符是新引进的,使用例子如下:
// 下面的作用和: @property(retain) MyClass *myObject;相同 |
@property(strong) MyClass *myObject; |
// 下面的作用和"@property(assign) MyClass *myObject;"相识 |
// 不同的地方在于,如果MyClass的实例析构后,这个属性变量的值变成nil,而不是一个野指针, |
|
@property(weak) MyClass *myObject; |
Variable Qualifiers
You use the following lifetime qualifiers for variables just like you would, say, const
.
__strong |
__weak |
__unsafe_unretained |
__autoreleasing |
__strong
is the default. __weak
specifies a zeroing weak reference to an object. __unsafe_unretained
specifies weak reference to an object that is not zeroing—if the object it references is deallocated, the pointer is left dangling. You use__autoreleasing
to denote arguments that are passed by reference (id *
) and are autoreleased on return.
Take care when using __weak
variables on the stack. Consider the following example:
NSString __weak *string = [[NSString alloc] initWithFormat:@"First Name: %@", [self firstName]]; |
NSLog(@"string: %@", string); |
Although string
is used after the initial assignment, there is no other strong reference to the string object at the time of assignment; it is therefore immediately deallocated. The log statement shows that string
has a null value.
You also need to take care with objects passed by reference. The following code will work:
NSError *error = nil; |
BOOL OK = [myObject performOperationWithError:&error]; |
if (!OK) { |
// Report the error. |
// ... |
However, the error declaration is implicitly:
NSError * __strong e = nil; |
and the method declaration would typically be:
-(BOOL)performOperationWithError:(NSError * __autoreleasing *)error; |
The compiler therefore rewrites the code:
NSError __strong *error = nil; |
NSError __autoreleasing *tmp = error; |
BOOL OK = [myObject performOperationWithError:&tmp]; |
error = tmp; |
if (!OK) { |
// Report the error. |
// ... |
The mismatch between the local variable declaration (__strong
) and the parameter (__autoreleasing
) causes the compiler to create the temporary variable. You can get the original pointer by declaring the parameter id __strong *
when you take the address of a __strong
variable. Alternatively you can declare the variable as __autoreleasing
.
Use Lifetime Qualifiers to Avoid Strong Reference Cycles
You can use lifetime qualifiers to avoid strong reference cycles. For example, typically if you have a graph of objects arranged in a parent-child hierarchy and parents need to refer to their children and vice versa, then you make the parent-to-child relationship strong and the child-to-parent relationship weak. Other situations may be more subtle, particularly when they involve block objects.
In manual reference counting mode, __block id x;
has the effect of not retaining x
. In ARC mode, __block id x;
defaults to retaining x
(just like all other values). To get the manual reference counting mode behavior under ARC, you could use__unsafe_unretained __block id x;
. As the name __unsafe_unretained
implies, however, having a non-retained variable is dangerous (because it can dangle) and is therefore discouraged. Two better options are to either use __weak
(if you don’t need to support iOS 4 or OS X v10.6), or set the __block
value to nil
to break the retain cycle.
The following code fragment illustrates this issue using a pattern that is sometimes used in manual reference counting.
MyViewController *myController = [[MyViewController alloc] init…]; |
// ... |
myController.completionHandler = ^(NSInteger result) { |
[myController dismissViewControllerAnimated:YES completion:nil]; |
}; |
[self presentViewController:myController animated:YES completion:^{ |
[myController release]; |
}]; |
As described, instead, you can use a __block
qualifier and set the myController
variable to nil
in the completion handler:
__block MyViewController *myController = [[MyViewController alloc] init…]; |
// ... |
myController.completionHandler = ^(NSInteger result) { |
[myController dismissViewControllerAnimated:YES completion:nil]; |
myController = nil; |
}; |
Alternatively, you can use a temporary __weak
variable. The following example illustrates a simple implementation:
MyViewController *myController = [[MyViewController alloc] init…]; |
// ... |
__weak MyViewController *weakMyViewController = myController; |
myController.completionHandler = ^(NSInteger result) { |
[weakMyViewController dismissViewControllerAnimated:YES completion:nil]; |
}; |
For non-trivial cycles, however, you should use:
MyViewController *myController = [[MyViewController alloc] init…]; |
// ... |
__weak MyViewController *weakMyController = myController; |
myController.completionHandler = ^(NSInteger result) { |
MyViewController *strongMyController = weakMyController; |
if (strongMyController) { |
// ... |
[strongMyController dismissViewControllerAnimated:YES completion:nil]; |
// ... |
} |
else { |
// Probably nothing... |
} |
}; |
In some cases you can use __unsafe_unretained
if the class isn’t __weak
compatible. This can, however, become impractical for nontrivial cycles because it can be hard or impossible to validate that the __unsafe_unretained
pointer is still valid and still points to the same object in question.
自动释放池
使用ARC,你不能使用NSAutoReleasePool类来管理自动释放池了,作为替代,ARC使用一个新的语法结构:
@autoreleasepool { |
// Code, such as a loop that creates a large number of temporary objects. |
} |
编译器根据工程是否使用ARC,来决定这个语法结构最终呈现方式,这个语法结构使用了一种比NSAutoReleasePool
更高效的方式。
Outlets
The patterns for declaring outlets in iOS and OS X change with ARC and become consistent across both platforms. The pattern you should typically adopt is: outlets should be weak
, except for those from File’s Owner to top-level objects in a nib file (or a storyboard scene) which should be strong
.
Outlets that you create should will therefore generally be weak
by default:
Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership.
The
strong
outlets are frequently specified by framework classes (for example,UIViewController
’sview
outlet, orNSWindowController
’swindow
outlet).
For example:
@interface MyFilesOwnerClass : SuperClass |
@property (weak) IBOutlet MyView *viewContainerSubview; |
@property (strong) IBOutlet MyOtherClass *topLevelObject; |
@end |
In cases where you cannot create a weak reference to an instance of a particular class (such as NSTextView
), you should use assign
rather than weak
:
@property (assign) IBOutlet NSTextView *textView; |
This pattern extends to references from a container view to its subviews where you have to consider the internal consistency of your object graph. For example, in the case of a table view cell, outlets to specific subviews should again typically beweak
. If a table view contains an image view and a text view, then these remain valid so long as they are subviews of the table view cell itself.
Outlets should be changed to strong
when the outlet should be considered to own the referenced object:
As indicated previously, this often the case with File’s Owner: top level objects in a nib file are frequently considered to be owned by the File’s Owner.
You may in some situations need an object from a nib file to exist outside of its original container. For example, you might have an outlet for a view that can be temporarily removed from its initial view hierarchy and must therefore be maintained independently.
其他的新功能
使用ARC技术,可以使得在栈上分配的指针隐式的初始化为nil,比如
- (void)myMethod { |
NSString *name; |
NSLog(@"name: %@", name); |
} |
上面的代码会Log出来一个null,不会象不使用ARC技术的时候使得程序崩溃。
iPhone之IOS5内存管理(ARC技术概述)的更多相关文章
- OC内存管理(ARC)
1.什么是ARC Automatic Reference Counting,自动引用计数,即ARC,可以说是WWDC2011和iOS5所引入 的最大的变革和最激动人心的变化.ARC是新的LLVM 3. ...
- IOS基础之 (十一) 内存管理 ARC
一 内存管理 1. set 方法内存管理的相关参数 retain: release旧值,retain新值(值适用于OC对象) assign:直接赋值(set方法默认,适用于非OC对象类型,即基本数据类 ...
- iPhone/Mac Objective-C内存管理教程和原理剖析
http://www.cocoachina.com/bbs/read.php?tid-15963.html 版权声明 此文版权归作者Vince Yuan (vince.yuan#gmail.com)所 ...
- iOS内存管理 ARC与MRC
想驾驭一门语言,首先要掌握它的内存管理特性.iOS开发经历了MRC到ARC的过程,下面就记录一下本人对iOS内存管理方面的一些理解. 说到iOS开发,肯定离不开objective-c语言(以下简称OC ...
- OC 内存管理之自动内存管理ARC
一.基本简介 ARC是自iOS 5之后增加的新特性,完全消除了手动管理内存的烦琐,编译器会自动在适当的地方插入适当的retain.release.autorelease语句.你不再需要担心内存管理,因 ...
- 7.2内存管理-ARC
@0-简介 1编译器会自动在适当的地方插入适当的retain.release.autorelease语句 @1-ARC的判断原则 1只要还有一个强指针变量指向对象,对象就会保持在内存中 2强指针 ...
- iOS 内存管理arc
http://www.tekuba.net/program/346/ ios自动释放池(autoreleasepool #import <Foundation/Foundation.h> ...
- 内存管理-ARC
推荐文章:http://blog.csdn.net/primer_programer/article/details/14442899 strong:强指针,指向对象,会持有对象,只有当对象无stro ...
- iOS MRC ARC 内存管理
转自:http://www.jianshu.com/p/48665652e4e4 1. 什么是内存管理 程序在运行的过程中通常通过以下行为,来增加程序的的内存占用 创建一个OC对象 定义一个变量 调用 ...
随机推荐
- Codeforces Round #363 (Div. 2) A、B、C
A. Launch of Collider time limit per test 2 seconds memory limit per test 256 megabytes input standa ...
- 论Spark高手是怎样炼成的
SPARK J大数据的处理怎么能变快一点,答案是请用spark,因为它是基于内存的,可以有效减少数据的落地次数.Spark性能超过Hadoop百倍,从多迭代批量处理出发,兼收并蓄数据仓库.流处理和图计 ...
- RxJava+RxAndroid+MVP入坑实践(基础篇)
转载请注明出处:http://www.blog.csdn.net/zhyxuexijava/article/details/51597230.com 前段时间看了MVP架构和RxJava,最近也在重构 ...
- 20165332 学习基础和C语言基础调查
学习基础和c语言基础调查 一.技能学习经验 从小学过很多东西,架子鼓.电子琴.街舞.吉他.书法.美术......爱好也有很多,乒乓球.篮球.唱歌......这么多项技能,要说那一项比大多数人好,还真的 ...
- Educational Codeforces Round 23E
题意:刚开始有一个空集合,现在有三种操作1,加x到集合中,2,删去集合中的一个x,3,查询集合中的x^p<l的个数 套路题,(看到异或和集合操作条件反射01字典树),加和删操作不说了,主要是查询 ...
- WSL安装xfce4
参考:https://github.com/Microsoft/WSL/issues/637 安装组件 1. win10 上安装 Xming https://sourceforge.net/proje ...
- MYSQL(python)安装记录
捯饬了很长时间,终于安装成功了,特此记录下! MYSQL历史版本下载,一般为绿色版本 地址:http://downloads.mysql.com/archives/community/ MYSQL安装 ...
- idea远程debug调试设置
1.idea设置 1.1 加入Tomcat Server选择Remote 1.2:设置对应的參数 xxx.xxx.152.67:8080为远程Tomcatserver的IP地址和port,这里能够设置 ...
- DRF 中 解决跨域 与 预检
DRF 中 解决跨域 与 预检 1 跨域 浏览器的同源策略: 对ajax请求进行阻拦 ps: 对href src属性 不限制 只有浏览器会阻止,requests模块不会存在跨域 (1)解决方案1 JS ...
- Android 系统信息的获取
Android 系统信息的获取 一.内存(ram): 1.android 的内存大小信息存放在系统的 /proc/meminfo 文件里面,通过adb shell 进入 手机目录后,使用 cat /p ...