黑马程序员——OC语言加强---ARC使用特点及注意事项

来源:互联网 发布:c 棋牌游戏源码 编辑:程序博客网 时间:2024/05/22 02:19

                                                                       ------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

ARC使用特点及注意事项

1、ARC特点总结

(1)不允许调用release,retain,retainCount 

(2)允许重写dealloc,但是不允许调用[super dealloc] 

(3)@property的参数:

strong:相当于原来的retain(适用于OC对象类型),成员变量是强指针

weak:相当于原来的assign,(适用于oc对象类型),成员变量是弱指针

assign:适用于非OC对象类型(基础类型)

 在ARC下 @propertyset方法参数

原子性\读写和MRC下是一样的

 MRC

ARC

assign

assign

retain

strong(强指针)OC其他的对象    weak(弱指针) UI控件

copy

copy 

2、ARC使用注意事项

1)ARC中,只要弱指针指向的对象不在了,就直接把弱指针做清空(赋值为nil)操作。

2)__weak Person *p=[[Person alloc]init];//不合理,对象一创建出来就被释放掉,对象释放掉后,ARC把指针设置为nil。

 __weak Student *stu = [Student new];

 //1  Studentnew

       //   产生空间

 //2 弱指针 stu 指向

 //弱指针指向对象销毁的过程

        //1) 释放对象空间

        //2)stu = nil

3)ARC中在property处不再使用retain,而是使用strong,在dealloc中不需要再

[superdealloc]。

@property(nonatomic,strong)Dog*dog;

//意味着生成的成员变量_dog是一个强指针,相当于以前的retain。

4)如果换成是弱指针,则换成weak,不需要加__。 

<span style="font-size:14px;">#import <Foundation/Foundation.h>@interface Student : NSObject@property(nonatomic,assign) int age;@end@implementation Student- (void)dealloc{    NSLog(@"Student dealloc");}@endint main(int argc, const char * argv[]) {    @autoreleasepool {                //1  Student new        //   产生空间        //2  弱指针 stu 指向        //弱指针指向对象销毁的过程        //1) 释放对象空间        //2) stu = nil        __weak Student *stu = [Student new];                NSLog(@"%d",stu.age);  // [nil age];    }    return 0;}</span>
0 0