保留/复制自动释放的对象 [英] Retain/copy of autoreleased objects

查看:78
本文介绍了保留/复制自动释放的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保我在这里正确理解了内存管理.在这里,是否有任何特定的原因要使用一种assignCurrentDate方法而不是另一种方法? 而且,所有这些都不会导致内存泄漏,对吗?

I want to make sure I understand the memory management correctly here. Is there any particular reason to use one of the assignCurrentDate methods over another here? Also, all of these result in no memory leaks, correct?

在.h中,我们有:

NSDate *currentDate1;
NSDate *currentDate2;
NSDate *currentDate3;
NSDate *currentDate3; 
//and 
@property (nonatomic, retain) NSDate *currentDate1;
@property (nonatomic, retain) NSDate *currentDate2;
@property (nonatomic, retain) NSDate *currentDate3;
@property (nonatomic, retain) NSDate *currentDate4;

.m中的

:

-(void) assignCurrentDate1
{
currentDate1 = [[NSDate date]retain];
//[NSDate date] is autoreleased
}

-(void) assignCurrentDate2
{
currentDate2 = [[NSDate date]copy]; 
}

-(void) assignCurrentDate3
{
self.currentDate3 = [NSDate date];
}

-(void) assignCurrentDate4
{
currentDate4 = [[NSDate alloc]init];
//[[NSDate alloc]init] is not autoreleased.
}

-(IBAction) printDate
{
NSLog ("%@", currentDate1);
NSLog ("%@", currentDate2);
NSLog ("%@", currentDate3);
NSLog ("%@", currentDate4);
}

- (void)dealloc
{
[currentDate1 release];
[currentDate2 release];
[currentDate3 release];
[currentDate4 release];
[super dealloc];
}

推荐答案

iOS内存管理的经验法则是:

The rule of thumb when it comes to iOS memory management is:

对于每个allocretaincopynew,您必须具有对应的releaseautorelease.

For every alloc, retain, copy, or new, you must have a corresponding release or autorelease.

实际上您在多个地方泄漏. 在标头中,您retain您的日期对象,然后在您的dealloc方法中释放它们.那是正确的.但是,在assignDate方法中,您无法释放副本或保留日期.自动发布[NSDate date]时,您将自己保留和复制它们.

You are leaking in several places actually. In your header, you retain your date objects and then in your dealloc method you release them. That is correct. However, In your assignDate methods, you fail to release the copy or retained date. While [NSDate date] is autoreleased, you are retaining and copying them yourself.

没有理由使用您的assignCurrentDate方法.您可以在init方法中执行以下操作:

There is no reason to use your assignCurrentDate methods. You can just do something like the following in your init method:

self.currentDate1 = [NSDate date];

就是这样.

(好吧,这不是 .)

就像吉姆在评论中指出的那样:

As Jim points out in the comments:

标头中的保留表示这些属性的综合设置器将保留分配给它们的对象.但是,如果看一下assign *方法,您将看到只有assignCurrentDate3实际上使用了该属性.其余的绕过综合的setter直接分配给ivar,因此在分配时不会保留它们.

The retain in the header signifies that the synthesized setter for those properties will retain objects assigned to them. But if you look at the assign* methods, you'll see that only assignCurrentDate3 actually uses the property. The rest assign directly to the ivar, bypassing the synthesized setter, so they aren't retained upon assignment.

这篇关于保留/复制自动释放的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆