ARC基本原理
是一个编译器特性,编译器在发现alloc对象,插入release的代码。不同于java的垃圾回收机制,是运行时机制。ARC的判断机制:只要没有强指针指向对象就会释放对象。
强指针:默认情况下所有指针都是强指针__strong
弱指针:__weak
ARC的使用
在创建项目的时候勾选Automatic Reference Counting,在开发过程中内存相关的操作如retain、release、autorelease等已不可调用。
#import<Foundation/Foundation.h> @class Dog @interface Person:NSObject @property(nonatomic,strong) Dog *dog;//原为(nonatomic,retain) @end -(void)dealloc { //[_dog release];此句不用再写 //[super dealloc];此句不允许调用 }
PS:
1、不允许调用release、retain、retainCount
2、允许重写dealloc,但不允许调用[supper alloc]
3、@property的参数
strong强指针,取代原来的retain(适用于OC对象)
week弱指针
原项目转化为ARC
Edit-》Refactor-》Convert to object-c ARC
查看项目是否为ARC项目
点击项目build settings找到object-c automatic reference counting选项yes是arc
设置项目有些文件非arc(项目既兼容ARC又兼容非ARC)
点击项目build phases -》compile source-》选中非arc文件双击填入-fno-objc-arc
或者非arc项目设置arc填入-f-objc-arc
ARC的循环引用
解决方式为一个strong一个week
Person.h @class Card @interface Person :NSObject @property(nonatomic,strong) Card *card; @end Card.h @class Person//仅仅告诉编译器Person是个类 @interface Card :NSObject @property(nonatomic,week) Person *person; @end