Objective-C - ARC(Automatic Reference Counting)自动引用技术详解

ARC特点与判断准则

/*
 ARC的判断准则:只要没有强指针指向对象,就会释放对象


 1.ARC特点
 1> 不允许调用release、retain、retainCount
 2> 允许重写dealloc,但是不允许调用[super dealloc]
 3> @property的参数
  * strong :成员变量是强指针(适用于OC对象类型)
  * weak :成员变量是弱指针(适用于OC对象类型)
  * assign : 适用于非OC对象类型
 4> 以前的retain改为用strong

 指针分2种:
 1> 强指针:默认情况下,所有的指针都是强指针 __strong
 2> 弱指针:__weak

 */

int main()
{
    Dog *d = [[Dog alloc] init];

    Person *p = [[Person alloc] init];
    p.dog = d;

    d = nil;

    NSLog(@"%@", p.dog);

    return 0;
}

void test()
{
    // 错误写法(没有意义的写法)
    __weak Person *p = [[Person alloc] init];


    NSLog(@"%@", p);

    NSLog(@"------------");
}
@class Dog;

@interface Person : NSObject

@property (nonatomic, strong) Dog *dog;


@property (nonatomic, strong) NSString *name;

@property (nonatomic, assign) int age;

@end
@implementation Person

- (void)dealloc
{
    NSLog(@"Person is dealloc");

    // [super dealloc];
}

@end
@interface Dog : NSObject

@end
@implementation Dog
- (void)dealloc
{
    NSLog(@"Dog is dealloc");
}
@end

ARC循环引用问题


/**
 *   当两端循环引用的时候,解决方案:
 1> ARC
 1端用strong,另1端用weak

 2> 非ARC
 1端用retain,另1端用assign
 */
int main()
{
    Person *p = [[Person alloc] init];


    Dog *d = [[Dog alloc] init];
    p.dog = d;
    d.person = p;

    return 0;
}
@class Dog;

@interface Person : NSObject

@property (nonatomic, strong) Dog *dog;

@end
@implementation Person

- (void)dealloc
{
    NSLog(@"Person--dealloc");
}

@end
@class Person;

@interface Dog : NSObject

@property (nonatomic, weak) Person *person;

@end
@implementation Dog
- (void)dealloc
{
    NSLog(@"Dog--dealloc");
}
@end
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值