在舊版 Objective-C 專案(手動參考計數 MRC 環境)中,開發者常需動態向 UIScrollView 添加大量子視圖控制器的 view,並在重新整理或釋放時,正確移除並釋放舊的子視圖,避免記憶體洩漏或重疊顯示錯誤。
@interface UIView (SubviewDetection)
- (BOOL)containsSubview:(UIView *)targetView;
@end
@implementation UIView (SubviewDetection)
- (BOOL)containsSubview:(UIView *)targetView {
if ([self.subviews containsObject:targetView]) {
return YES;
}
for (UIView *subview in self.subviews) {
if ([subview containsSubview:targetView]) {
return YES;
}
}
return NO;
}
@end
// 移除單一子視圖(MRC 環境)
if ([scrollDetail containsSubview:detailVC.view]) {
[detailVC.view removeFromSuperview];
[detailVC release]; // 僅在 MRC 下需要
detailVC = nil;
}
// 批量清理所有子視圖
for (UIView *subview in [scrollDetail.subviews copy]) { // copy 避免遍歷中修改陣列崩潰
[subview removeFromSuperview];
// 若 subview 持有控制器引用,需額外 release 對應 controller
}
若專案已遷移至 ARC(Automatic Reference Counting),流程大幅簡化:
release,removeFromSuperview 即切斷強引用。addChildViewController: / removeFromParentViewController 管理生命週期。UICollectionView 或 UITableView 替代手動管理 ScrollView 子視圖,效能與維護性更優。[array copy] 或反向迴圈。viewDidDisappear)不被呼叫。