简要剖析ARC

简介: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四个修饰符作为变量修饰。
  1. __strong是默认的,意味着只要是有强引用指向它,就是激活状态。  
  2. __weak 意味着当没有强引用给这个对象时候,自动设置成nil。
  3. __unsafe_unretain相比于__weak区别是当没有强引用这个对象时候,不会置为nil,也就是变为野指针。
  4. __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块,当持续需要频繁创建大量临时对象时候可以放在自动释放池块里面来做


  •  牵狗模型
假设狗是我们的对象,狗要跑了比作是销毁了,人牵着狗狗就不会跑是强引用,而一群小孩看到狗,说那有只狗比作弱引用,当狗跑了也就释放了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值