直到昨天我还以为我已经了解了 iPhone 的内存管理。 这是我的问题:
// .h file
@property(nonatomic, retain) NSMutableDictionary *dicParams;
@property(nonatomic, retain) NSMutableDictionary *dicReferences;
@property(nonatomic, retain) FtMonitorHandler *monitorHandler;
// .m file
@synthesize dicParams, dicReferences, monitorHandler;
- (id)init {
self = [super init];
if (self) {
self.dicParams = [[NSMutableDictionary alloc] init];
self.dicReferences = [[NSMutableDictionary alloc] init];
self.monitorHandler = [[FtMonitorHandlerService alloc] init];
}
return self;
}
- (void)dealloc {
[monitorHandler release];
[dicParams release];
[dicReferences release];
[super dealloc];
}
如果我在其他地方设置,例如在 View Controller 分配之后
self.dicParams = dicValues;
…它会变成泄漏
我对用“self....”设置实例变量的理解是,当前值将被“释放”,然后用“retain”设置。
我尝试了一些乐器。结果:
-(void)createLeak {
self.dicParams = [[NSMutableDictionary alloc] init];
self.dicParams = [[NSMutableDictionary alloc] init];
}
-(void)createAnotherLeak {
self.dicParams = [[NSMutableDictionary alloc] init];
self.dicParams = nil;
self.dicParams = [[NSMutableDictionary alloc] init];
}
- (void)createWithoutLeak {
if(dicParams != nil) [dicParams release];
self.dicParams = [[NSMutableDictionary alloc] init];
}
我是否错过了什么,或者这是应该的行为吗?
编辑:我尝试实现建议的更改。只要我的变量不是 GUI 元素,它就可以正常工作。 (UIView、UILabel 等)
内存警告后自动释放将导致应用程序崩溃
- (void)loadView {
[super loadView];
// ... here is some other stuff ...
self.lblDeparture = [[[UILabel alloc] init] autorelease];
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
self.lblDeparture = nil;
}
- (void)dealloc {
[lblDeparture release];
[super dealloc];
}
我不太确定,但我认为以下几行是真正的问题:
CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, INFO_VIEW_HEIGHT);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
[imageView addSubview:lblDeparture];
[lblDeparture release]; // is this correct?
[self.view addSubview:imageView];
[imageView release];
最佳答案
如果你初始化,你需要自动释放。
-(void)dontCreateAnotherLeak {
self.dicParams = [[[NSMutableDictionary alloc] init] autorelease];
self.dicParams = nil;
self.dicParams = [[[NSMutableDictionary alloc] init] autorelease];
}
更简单的等效方法是使用便捷访问器。
self.dicParams = [NSMutableDictionary dictionary];
如果您想自己处理这个问题。在 @synthesize dictParams 之上;您还需要创建自己的 setter。
-(void)setDictParams:(NSMutableDictionary*) newDictParams
{
if (dictParams != newDictParams)
{
[dictParams release];
dictParams = [newDictParams retain];
}
}
这有点简单。但本质上是编译器通过添加到 @property 标记的保留修饰符创建的内容
关于iphone - 使用 "self.variable = value"设置实例变量两次会导致内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5659389/