gpt4 book ai didi

iOS 开发者 PageControl 示例优化

转载 作者:行者123 更新时间:2023-12-01 16:59:40 28 4
gpt4 key购买 nike

我正在尝试为 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 开始。从父 View 中删除 vc.view 后,它保持在 3。在 vc.view 设置为 nil 后,它下降到 2。从 viewControllers 数组中删除 vc 后,它保持在 2。

我的问题是(仍然):为什么不调用 viewDidUnload ?

提前致谢

最佳答案

来自 UIViewController引用 viewDidUnload

When a low-memory condition occurs and the current view controller’s views are not needed, the system may opt to remove those views from memory. This method is called after the view controller’s view has been released and is your chance to perform any final cleanup.



viewDidUnload 只会在系统从内存中删除这些 View 时发生。如果您在硬件菜单下的模拟器上发出内存警告,这些方法应该会被触发。

关于iOS 开发者 PageControl 示例优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8350670/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com