Cep*_*phi 4 iphone memory-management objective-c
我想确保我在这里正确理解内存管理.有没有什么特别的理由在这里使用其中一个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;
Run Code Online (Sandbox Code Playgroud)
在他们中:
-(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];
}
Run Code Online (Sandbox Code Playgroud)
iOS内存管理的经验法则是:
对于每一个
alloc,retain,copy,或者new,你必须有一个相应的release或autorelease.
你实际上是在几个地方泄漏.在标题中, 在assignDate方法中,您无法释放副本或保留日期.虽然retain您是日期对象,然后在dealloc方法中释放它们.那是正确的.但是,[NSDate date]是自动释放,但您自己保留并复制它们.
没有理由使用您的assignCurrentDate方法.您可以在init方法中执行以下操作:
self.currentDate1 = [NSDate date];
Run Code Online (Sandbox Code Playgroud)
而已.
编辑:(好吧,那不是.)
正如吉姆在评论中指出的那样:
标题中的保留表示这些属性的合成setter将保留分配给它们的对象.但是如果你看一下assign*方法,你会发现只有assignCurrentDate3实际上使用了该属性.其余的直接分配到ivar,绕过合成的setter,因此在分配时不会保留它们.
| 归档时间: |
|
| 查看次数: |
670 次 |
| 最近记录: |