这个代码是正确的内存管理 - 对于一个基本的自定义类

时间:2011-05-24 20:58:25

标签: iphone objective-c ios memory-management

我是否需要在此处添加/修改任何内容以进行自定义类的内存管理? (例如,所需的任何“释放”行,不需要dealloc方法吗?)

#import <Foundation/Foundation.h>
@interface TimelineItem : NSObject {
    NSDate *_startDate;
    BOOL _working;
    BOOL _coreWeekend;
}
@property (nonatomic, retain) NSDate *startDate;
@property (nonatomic) BOOL working;
@property (nonatomic) BOOL coreWeekend;
- (id)initWithStartDate:(NSDate*)startDate Working:(BOOL)working CoreWeekend:(BOOL)coreWeekend;
@end



#import "TimelineItem.h"
@implementation TimelineItem
@synthesize startDate = _startDate;
@synthesize working = _working;
@synthesize coreWeekend = _coreWeekend;
- (id)initWithStartDate:(NSDate*)startDate Working:(BOOL)working CoreWeekend:(BOOL)coreWeekend {
    if (self == [super init])
    {
        // Initialization
        self.startDate = startDate;
        self.working = working;
        self.coreWeekend = coreWeekend;
    }
    return self;
}
@end

3 个答案:

答案 0 :(得分:4)

不,不是。您通过将您的媒体资源声明为retainedstartDate (retain)参数。这意味着您在某个时候负责releasing它。您可以通过添加:

来解决此问题
- (void)dealloc {
  [_startDate release];
  [super dealloc];
}

此外,您不应该在init方法名称中大写“Working”和“CoreWeekend”。它们应该分别是“工作”和“coreWeekend”。

答案 1 :(得分:3)

您需要实施-dealloc并在那里发布startDate。否则,这似乎没问题。

- (void)dealloc {
    [_startDate release];
    [super dealloc];
}

答案 2 :(得分:2)

您需要在取消分配类时释放_startDate。由于您拥有属性,最安全的做法是将其设置为nil,并且自动生成的setter将负责为您释放它。

- (void)dealloc
{
    self.startDate = nil;
    [super dealloc];
}