我想确保我在这里正确理解内存管理。是否有任何特殊原因要在这里使用一种 allocateCurrentDate 方法而不是另一种方法?
另外,所有这些都不会导致内存泄漏,对吗?
在 .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;
在他们中:
-(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 内存管理的经验法则是:
对于每一个alloc
, retain
, copy
, or new
,你必须有一个相应的release
or autorelease
.
实际上,您在几个地方泄漏了。 在你的标题中,你retain
您的日期对象,然后在您的 dealloc 方法中释放它们。那是对的。但是, 在您的 allocateDate 方法中,您无法释放副本或保留日期。尽管[NSDate date]
是自动发布的,您自己保留并复制它们。
没有理由使用你的assignCurrentDate
方法。您可以在 init 方法中执行类似以下操作:
self.currentDate1 = [NSDate date];
就是这样。
Edit:(好吧,那就是not it.)
正如吉姆在评论中指出的那样:
标头中的保留表示这些属性的综合设置器将保留分配给它们的对象。但如果您查看 allocate* 方法,您会发现只有 allocateCurrentDate3 实际使用该属性。其余的直接分配给 ivar,绕过合成的 setter,因此它们在分配时不会被保留。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)