ARC 自动引用计数 ARC不是垃圾回收,而是编译器自动插入代码来减少程序员的代码输入和失误。 同时比垃圾和效率要高,因为其不影响运行时间,相当于自己管理内存。 总是通过属性来管理实例变量(init/dealloc除外),在dealloc中释放所有属性。 dealloc中会自动加入释放实例变量的代码,因此不必要手段增加释放实例变量的代码。不需要手动调用[super dealloc] 不要调用retain,release,autorelease,编译器会自动插入相关代码。 注意命名方式,不要以copyXXX方式命名不想进行retain的方法,编译器会根据方法名自动retain。 C语言结构体中不要有对象指针 id和void*只能通过桥接转换来进行转换 不要使用NSAutoreleasePool,而是使用@autoreleasepool{}代码块。 转换ARC代码:Edit->Refactor->Convert to Objective-C ARC strong 相当于retain。 Strong在ARC环境为默认属性类型。 @property (nonatomic,readwrite,strong)NSString *title; @property (strong, nonatomic) UIViewController *viewController; @property (nonatomic, strong) id childObject; Default weak 取代之前的assign,对象销毁之后会自动置为nil,防止野指针。 Assign不能自动置为nil,需要手动置为nil。 Delegate基本总是使用weak,以防止循环引用。特殊情况是,希望在dealloc中调用delegate的某些方法进行释放,此时如果使用weak将引起异常,因为此时已经是nil了,那么采用assign更为合适。 @property (weak, nonatomic) IBOutlet UIButton *myButton;//处于最顶层的IBOutlet应该为strong @property (nonatomic, weak) id parentObject; @property(nonatomic,readwrite,weak) id <MyDelegate> delegate; @property (nonatomic, weak) NSObject <SomeDelegate> *delegate; assign 对基础数据类型(NSInteger,CGFloat)和C数据类型(int, float, double, char等) ’@property (nonatomic, assign) int n; @property (nonatomic, assign) BOOL isOK; @property (nonatomic, assign) CGFloat scalarFloat; @property (nonatomic, assign) CGPoint scalarStruct; Default retain NSObject及其子类。 Release旧值,retain新值。 Retain是指针复制(浅复制),引用计数加1,而不会导致内容被复制。 @property (nonatomic, retain)UIColor *myColor; atomic Default nonatomic 非原子性访问,对属性赋值的时候不加锁,多线程并发访问会提高性能 unsafe_unretained copy 复制内容(深复制),如果调用copy的是数组,则为指针复制(浅复制),仅仅复制子元素的指针。 @property (nonatomic,copy)NSString *title; @property (nonatomic, copy) NSMutableArray *myArray;//not recommended @property (nonatomic, copy) SomeBlockType someBlock; readonly readwrite Default retain cycle 循环保留 delegate和block是产生retain cycle的主要原因 dealloc 移除观察者observers 注销通知notification 设置非weak的delegate为nil 取消timer |
|