直到昨天,我認爲我已經瞭解了iPhone的內存管理。 那麼這裏是我的問題:用「self.variable = value」設置實例變量兩次會導致內存泄漏?
// .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];
}
如果設置了別的地方,例如
self.dicParams = dicValues;
的視圖 - 控制的分配後...它會變成一個泄漏
我的設置實例變量的理解與「自我......」是,當前值將被「釋放」,然後設置「保留」。
我嘗試了一下儀器。結果:
-(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];
爲什麼你使用self.yourObjects,你在同一個類中,而不是保留它(通過調用self.yourObject),你可以嘗試沒有自我。 – Ravin 2011-04-14 06:28:08
如果我用「variable = ...」分配變量兩次,那麼會不會有泄漏,因爲第一個引用將會消失?沒有「self.variable ...」 – user707342 2011-04-14 06:43:42
不,我說你應該嘗試用dicParams = [[NSMutableDictionary alloc] init]; 而不是self.dicParams = [[NSMutableDictionary alloc] init]; 。 – Ravin 2011-04-14 06:46:52