我是新來的可可/ objective-c,我正在爲我的對象發佈而感到苦惱。我有以下代碼:如何在forin循環中釋放對象?
gastroCategoryList = [[NSMutableArray alloc] init];
for (NSDictionary *gastrocategory in gastrocategories) {
NSString *oid = [gastrocategory objectForKey:@"id"];
GastroCategory *gc = [[GastroCategory alloc] initWithId:[oid intValue] name:[gastrocategory objectForKey:@"name"]];
[gastroCategoryList addObject:gc];
}
分析儀顯示我的「gastrocategory」的定義爲是一種潛在的內存泄漏。但我不確定我是否可以在for循環結束時釋放它?
此外,在下面的代碼:
- (NSArray *)eventsForStage:(int)stageId {
NSMutableArray *result = [[NSMutableArray alloc] init];
for (Event *e in eventList) {
if ([e stageId] == stageId) {
[result addObject:e];
}
}
return result;
}
分析儀告訴我,我的「結果」是一個潛在的泄漏。但是我應該在哪裏發佈這個?
是否還有一個簡單的規則來記住,當我應該使用分配,複製,保留等在@property?
另一個問題:
- (IBAction)showHungryView:(id)sender {
GastroCategoriesView *gastroCategoriesView = [[GastroCategoriesView alloc] initWithNibName:@"GastroCategoriesView" bundle:nil];
[gastroCategoriesView setDataManager:dataManager];
UIView *currentView = [self view];
UIView *window = [currentView superview];
UIView *gastroView = [gastroCategoriesView view];
[window addSubview:gastroView];
CGRect pageFrame = currentView.frame;
CGFloat pageWidth = pageFrame.size.width;
gastroView.frame = CGRectOffset(pageFrame,pageWidth,0);
[UIView beginAnimations:nil context:NULL];
currentView.frame = CGRectOffset(pageFrame,-pageWidth,0);
gastroView.frame = pageFrame;
[UIView commitAnimations];
//[gastroCategoriesView release];
}
我不明白這一點,在 「gastroCategoriesView」 是一個潛在的泄漏。我試圖在最後或autorelease釋放它,但都不能正常工作。每次我打電話給我的應用程序終止的方法。再一次非常感謝你!
非常感謝。你是否也知道@property問題的規則? – n3on 2011-03-23 19:15:08
@ n3on:如果一個屬性被聲明爲'retain'或'copy',則應該在你的類的'dealloc'方法中釋放它的ivar。 – BoltClock 2011-03-23 19:16:43
@BoltClock:好的,謝謝。但是,我應該何時使用複製,保留或分配? – n3on 2011-03-23 19:19:13