简介:ARC是在ios5(weak需要ios5才能使用)之后引入的一个新的内存管理机制,全称是Automatic Reference Counting,即自动引用计数,原理是系统在编译期间自动插入release/retain、autorelease管理对象的引用计数,并且处理dealloc方法里面的对象。
规则:
- 不要显示的调用dealloc方法(包括super dealloc),也不要再dealloc里面销毁对象,但是对于Core Foundtion可以使用CFReatin/CFRelease等方法释放资源。不要调用retain/release/autorelease方法。
- 不要使用NSAllocateObject or NSDeallocateObject,系统会自动回收通过alloc创建的对象。
- 不要使用C风格的结构体,可以用创建OC类来进行数据管理。
- 不再有id类型和void *类型的随意映射关系。
- 不要使用NSAutoreleasePool对象管理临时对象,ARC提供了 @autoreleasepool blcok闭包来替代,并且比NSAutoreleasePool效率更高。
- 不能使用内存空间,NSZone在运行时态被自动被忽略。
- 不要使用以new开头的命名变量。
ARC引进的新限定词(ARC Introduces New Lifetime Qualifiers)
- Property Attributes
增加了strong和weak两个关键字声明Property Attributes,默认情况是strong
// 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;
使用__weak变量创建之后会立刻被销毁
NSString * __weak string = [[NSString alloc] init];
NSLog(@"string: %@", string);
报警告对象在assing之后将会被release
- Variable Qualifiers(变量限定)
增加了__weak,__strong,__unsafe_unretain,__autoreleasing四个修饰符作为变量修饰。
- __strong是默认的,意味着只要是有强引用指向它,就是激活状态。
- __weak 意味着当没有强引用给这个对象时候,自动设置成nil。
- __unsafe_unretain相比于__weak区别是当没有强引用这个对象时候,不会置为nil,也就是变为野指针。
- __autorelesing 当ARC失效时候调用autorelease方法
正确声明变量修饰符
MyClass * __weak myWeakReference;
MyClass * __unsafe_unretained myUnsafeReference;
在blcok内部的变量,block都会copy一份来操作,blcok如果想要访问并修改外部变量,需要声明为__block。
MyViewController * __block myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler = ^(NSInteger result) {
[myController dismissViewControllerAnimated:YES completion:nil];
myController = nil;
};
打破引用循环:
可以使用__weak创建临时变量,__weak修饰的变量意味着当没有强引用的时候自动置为nil,打破循环引用
MyViewController *myController = [[MyViewController alloc] init…];
// ...
MyViewController * __weak weakMyViewController = myController;
myController.completionHandler = ^(NSInteger result) {
[weakMyViewController dismissViewControllerAnimated:YES completion:nil];
};
- 自动释放池block块
@autoreleasepool {
//在block体内的对象在最后一个括号结束之前,会收到一条autorelease消息,对每一个对象release
}
每一个线程默认都会管理一个自动释放池block块,当持续需要频繁创建大量临时对象时候可以放在自动释放池块里面来做
- 牵狗模型
假设狗是我们的对象,狗要跑了比作是销毁了,人牵着狗狗就不会跑是强引用,而一群小孩看到狗,说那有只狗比作弱引用,当狗跑了也就释放了。