码迷,mamicode.com
首页 > 其他好文 > 详细

oc内存管理黄金法则

时间:2015-11-16 22:43:11      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

ios笔记,如有错误,敬请告知,感谢不尽

1.When you create an object using new, alloc, or copy, the object has a
retain count of 1. You are responsible for sending the object a release or autorelease message when you’re finished with it. That way, it gets cleaned up when its useful life is over.

若用new、alloc、copy创建对象,对象的引用计数器为1。使用完毕后要发送release或autorelease消息给创建的对象。

 

2.When you get hold of an object via any other mechanism, assume it has
a retain count of 1 and that it has already been autoreleased. You don’t need to do any further work to make sure it gets cleaned up. If you’re going to hang on to the object for any length of time, retain it and make sure to release it when you’re finished.

通过其他方式获得的对象,比如下面三行代码技术分享

 技术分享

    Person * s = [[Person alloc]init];

    Person * s1 = s;

    [s retain];

 s1通过非new、alloc、copy方法获得一个对象,这时就要使用retain、release来维护对象的使用。

3.If you retain an object, you need to (eventually) release or autorelease it. Balance these retains and releases. 

手动管理一个对象要保证retain和release最终一样多。

 

ps:1.用@property(nonatomic,retain)声明的指针(引用)自动生成的setter、getter方法如下

-(void)set_student:(Student*)student{

    if (_student != student) {

        [_student release];

        _student = [student retain];

    }

}

-(Student*)student{

    return _student;

}

setter和getter里会release旧对象,retain新对象,所以我们用点运算符、set方法时不用特别retain引用的对象

2.两个对象的循环引用问题:@property(nonatomic,assign)来声明其中一个对象的引用就可以了

oc内存管理黄金法则

标签:

原文地址:http://www.cnblogs.com/lu-diary/p/4970142.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!