我正在尝试为iOS Developer PageControl Sample实现建议的优化。下面是我在PhoneContentController中使用的代码:
// A possible optimization would be to unload the views+controllers which are no longer visible
for (int i = 0; i < page-1; i++) {
MyViewController *vc = [viewControllers objectAtIndex:i];
if ((NSNull *)vc != [NSNull null]) {
NSLog(@"Unloading page %d", i);
[vc.view removeFromSuperview];
vc.view = nil;
[viewControllers replaceObjectAtIndex:i withObject:[NSNull null]];
}
}
for (int i = page+2; i < kNumberOfPages; i++) {
MyViewController *vc = [viewControllers objectAtIndex:i];
if ((NSNull *)vc != [NSNull null]) {
NSLog(@"Unloading page %d", i);
[vc.view removeFromSuperview];
vc.view = nil;
[viewControllers replaceObjectAtIndex:i withObject:[NSNull null]];
}
}这看起来工作正常。但是,我希望MyViewController中的viewDidUnload方法和dealloc方法都会被执行。我在这两个方法中都调用了NSLog():
- (void)viewDidUnload
{
NSLog(@"Page %d unloaded", pageNumber);
[super viewDidUnload];
}
- (void)dealloc
{
NSLog(@"Page %d destroyed", pageNumber);
[pageNumberLabel release];
[numberTitle release];
[numberImage release];
[super dealloc];
}似乎只调用了dealloc。下面是输出:
2011-12-02 01:13:38.829 PageControl[3560:207] Unloading page 0
2011-12-02 01:13:38.831 PageControl[3560:207] Page 0 destroyed
2011-12-02 01:13:39.597 PageControl[3560:207] Unloading page 1
2011-12-02 01:13:39.598 PageControl[3560:207] Page 1 destroyed
2011-12-02 01:13:40.437 PageControl[3560:207] Unloading page 2
2011-12-02 01:13:40.437 PageControl[3560:207] Page 2 destroyed我的问题是:为什么不调用viewDidUnload?
模拟内存不足警告没有任何区别。
我插入的NSLog语句如下:
if ((NSNull *)vc != [NSNull null]) {
UIView *vw = vc.view;
NSLog(@"1.vw[%d] -> %d", i, [vw retainCount]);
[vc.view removeFromSuperview];
NSLog(@"2.vw[%d] -> %d", i, [vw retainCount]);
vc.view = nil;
NSLog(@"3.vw[%d] -> %d", i, [vw retainCount]);
[viewControllers replaceObjectAtIndex:i withObject:[NSNull null]];
NSLog(@"4.vw[%d] -> %d", i, [vw retainCount]);
}retainCount从3开始。在vc.view从superview中删除后,它保持在3。在vc.view设置为nil后,它会降至2。在vc从viewControllers数组中移除后,它保持为2。
我的问题是:为什么不调用viewDidUnload?
提前致以问候和感谢
发布于 2011-12-02 09:37:19
来自viewDidUnload的UIViewController参考
当出现内存不足的情况并且不需要当前视图控制器的视图时,系统可能会选择从内存中删除这些视图。这个方法是在视图控制器的视图被释放之后调用的,它是您执行任何最终清理的机会。
只有当系统从内存中删除这些视图时,才会发生viewDidUnload。如果您在Hardware菜单下的模拟器上发出内存警告,这些方法应该会被触发。
https://stackoverflow.com/questions/8350670
复制相似问题