内存泄漏-是否在init中设置变量? [英] Memory leak -- setting variable in init?
问题描述
内存管理让我再次困惑-
Memory management has me confused again --
在我的.h文件中,我有:
In my .h file, I have:
@property (nonatomic,retain) NSMutableDictionary *properties;
在我的.m文件中,我具有以下init方法,该方法抱怨self.properties行上的Instruments泄漏:
In my .m, I have the following init method, which complains of a leak in Instruments on the self.properties line:
- (id) init {
self = [super init];
self.properties = [[NSMutableDictionary alloc] init];
return self;
}
如果我不使用访问器,它还会抱怨泄漏.
It also complains of a leak if I don't use the accessor.
同样,如果使用此策略,它会泄漏:
Likewise, it leaks if I use this strategy:
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
self.properties = temp;
[temp release];
在dealloc中,我有:
And in dealloc I have:
self.properties = nil;
[properties release];
我以为我在遵守规则,但这是在暗示我.
I thought I was following the rules, but this one is alluding me.
推荐答案
如果您的.h定义如下:
If your .h is defined like this:
@interface MDObject : NSObject {
NSMutableDictionary *properties;
}
@property (nonatomic, retain) NSMutableDictionary *properties;
@end
以下是.m可能的正确实现:
The following are possible correct implementations of your .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
记住这一点可能会有所帮助
It might be helpful to remember that
self.properties = [NSMutableDictionary dictionary];
与
[self setProperties:[NSMutableDictionary dictionary]];
为您综合的这2种方法看起来类似于以下内容:
Those 2 methods that are synthesized for you would look similar to the following:
- (NSMutableDictionary *)properties {
return properties;
}
- (void)setProperties:(NSMutableDictionary *)aProperties {
[aProperties retain];
[properties release];
properties = aProperties;
}
这篇关于内存泄漏-是否在init中设置变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!