内存泄漏 - 在init中设置变量?

jn_*_*pdx 1 memory-leaks memory-management objective-c

内存管理让我感到困惑 -

在我的.h文件中,我有:

@property (nonatomic,retain) NSMutableDictionary *properties;
Run Code Online (Sandbox Code Playgroud)

在我的.m中,我有以下init方法,它抱怨self.properties行上的Instruments泄漏:

- (id) init {
  self = [super init];

  self.properties = [[NSMutableDictionary alloc] init];

  return self;
}
Run Code Online (Sandbox Code Playgroud)

如果我不使用存取器,它也会抱怨泄漏.

同样,如果我使用此策略,它会泄漏:

NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];

self.properties = temp;

[temp release];
Run Code Online (Sandbox Code Playgroud)

在dealloc我有:

self.properties = nil;
[properties release];
Run Code Online (Sandbox Code Playgroud)

我以为我遵守了规则,但这个是暗示我的.

NSG*_*God 6

如果您的.h定义如下:

@interface MDObject : NSObject {
    NSMutableDictionary *properties;
}

@property (nonatomic, retain) NSMutableDictionary *properties;

@end
Run Code Online (Sandbox Code Playgroud)

以下是您.m的正确实现:

@implementation MDObject

- (id)init {
    if ((self = [super init])) {
         properties = [[NSMutableDictionary alloc] init];
    }
    return self;
}

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

@end
Run Code Online (Sandbox Code Playgroud)

要么

@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
Run Code Online (Sandbox Code Playgroud)

记住这一点可能会有所帮助

self.properties = [NSMutableDictionary dictionary];
Run Code Online (Sandbox Code Playgroud)

是相同的

[self setProperties:[NSMutableDictionary dictionary]];
Run Code Online (Sandbox Code Playgroud)

为您合成的这两种方法看起来类似于以下内容:

- (NSMutableDictionary *)properties {
    return properties;
}

- (void)setProperties:(NSMutableDictionary *)aProperties {
    [aProperties retain];
    [properties release];
    properties = aProperties;
}
Run Code Online (Sandbox Code Playgroud)