我是新手,涉及到cocoa / objective-c的东西让我很困惑,特别是对象的释放问题。我有以下代码:
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];
}
分析器显示我在for循环中定义的"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;
}
分析器告诉我我的“结果”可能会出现泄漏(leak)。但是我应该在哪里释放它呢?
在@property中,何时使用assign、copy、retain等有什么简单的记忆规则吗?
另一个问题:
- (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,但都无法正常工作。每次调用该方法时,我的应用程序都会终止。再次感谢您!
retain
或copy
,那么你应该在类的dealloc
方法中释放它的实例变量。 - BoltClock