jn_*_*pdx 1 memory-leaks memory-management objective-c
内存管理让我感到困惑 -
在我的.h文件中,我有:
@property (nonatomic,retain) NSMutableDictionary *properties;
在我的.m中,我有以下init方法,它抱怨self.properties行上的Instruments泄漏:
- (id) init {
  self = [super init];
  self.properties = [[NSMutableDictionary alloc] init];
  return self;
}
如果我不使用存取器,它也会抱怨泄漏.
同样,如果我使用此策略,它会泄漏:
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
self.properties = temp;
[temp release];
在dealloc我有:
self.properties = nil;
[properties release];
我以为我遵守了规则,但这个是暗示我的.
如果您的.h定义如下:
@interface MDObject : NSObject {
    NSMutableDictionary *properties;
}
@property (nonatomic, retain) NSMutableDictionary *properties;
@end
以下是您.m的正确实现:
@implementation MDObject
- (id)init {
    if ((self = [super init])) {
         properties = [[NSMutableDictionary alloc] init];
    }
    return self;
}
- (void)dealloc {
    [properties release];
    [super dealloc];
}
@end
要么
@implementation MDObject
- (id)init {
    if ((self = [super init])) {
         self.properties = [NSMutableDictionary dictionary];
    }
    return self;
}
- (void)dealloc {
    self.properties = nil; // while this works,
                           // [properties release] is usually preferred
    [super dealloc];
}
@end
记住这一点可能会有所帮助
self.properties = [NSMutableDictionary dictionary];
是相同的
[self setProperties:[NSMutableDictionary dictionary]];
为您合成的这两种方法看起来类似于以下内容:
- (NSMutableDictionary *)properties {
    return properties;
}
- (void)setProperties:(NSMutableDictionary *)aProperties {
    [aProperties retain];
    [properties release];
    properties = aProperties;
}