gpt4 book ai didi

iphone - 保留/复制自动释放的对象

转载 作者:太空狗 更新时间:2023-10-30 04:00:33 29 4
gpt4 key购买 nike

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

在 .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 内存管理的经验法则是:

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

实际上你在几个地方漏水了。 在您的 header 中,您 保留 您的日期对象,然后在您的 dealloc 方法中释放它们。那是正确的。但是, 在您的 assignDate 方法中,您未能释放副本或保留日期。虽然 [NSDate date] 是自动发布的,但您要自己保留和复制它们。

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

self.currentDate1 = [NSDate date];

就是这样。

编辑:(好的,不是。)

正如吉姆在评论中指出的那样:

header 中的 retain 表示这些属性的合成 setter 将保留分配给它们的对象。但是如果您查看 assign* 方法,您会发现实际上只有 assignCurrentDate3 使用该属性。其余部分直接分配给 ivar,绕过合成 setter,因此它们在分配时不会保留。

关于iphone - 保留/复制自动释放的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6416963/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com