我正在使用 Apple 的 Instruments “分配”工具,并注意到当我在两个视图之间来回切换时,分配总是会增长。调查,我发现所有的内存都来自我的 UIViewController 的 UIView 的子视图的对象。
我检查了一下,我的 UIViewController 正在被释放,但显然 UIView 不是?我没有将 UIView 与 UIView 控制器分开保留。有人有想法么?
这是我编写的用于在视图之间切换的代码。
UISubViewController *viewController = [UIViewControllerFactory createViewController:viewControllerID]; // Creates and returns a UIViewController by ID
[currentViewController viewWillDisappear:YES];
[currentViewController.view removeFromSuperview];
[currentViewController viewDidDisappear:YES];
[viewController viewWillAppear:YES];
[self.view insertSubview:viewController.view atIndex:0];
[viewController viewDidAppear:YES];
self.currentViewController = viewController;
[viewController release];
编辑:
好的,因为担心我只是使用 ViewController 的 View 然后释放 ViewController,所以我尝试了一个实验,在该实验中我创建了一个新类,它是 NIB 中的文件所有者,但继承自 NSObject。
代码现在看起来像这样:
MyView *myView = [[MyView alloc] initWithNibName:@"myView"];
[currentView viewWillDisappear:YES];
[currentView.view removeFromSuperview];
[currentView viewDidDisappear:YES];
[myView viewWillAppear:YES];
[self.view insertSubview:myView.view atIndex:0];
[myView viewDidAppear:YES];
self.currentView = myView;
[myView release];
MyView 的初始化程序如下所示:
@interface MyView : NSObject {
IBOutlet UIView *view;
NSArray *nibTopLevelObjects;
}
@property (nonatomic, retain) UIView *view;
- (id)initWithNibName:(NSString *)nibName;
@end
@implementation MyView
@synthesize view;
- (id)initWithNibName:(NSString *)nibName {
if (self = [super init]) {
nibTopLevelObjects = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
[nibTopLevelObjects retain];
}
return self;
}
- (void)dealloc {
[view release];
[nibTopLevelObjects release];
view = nil;
nibTopLevelObjects = nil;
[super dealloc];
}
@end
每次换入和换出新视图时,我仍然会看到视图的内存泄漏。
有什么新想法吗?