我在循环内实例化后调用 BaseViewController 类的 ARC 和 dealloc 时遇到了一个小问题,我不知道为什么。我想做的基本上是将所有基本 View Controller 存储在一个数组上。
@interface CategoriesContainerViewController ()
@property (nonatomic, strong) IBOutlet UIScrollView* scrollView;
@property (nonatomic, strong) NSMutableArray* categoriesViews;
@end
- (void)viewDidLoad {
[super viewDidLoad];
// Get the categories from a plist
NSString* path = [[NSBundle mainBundle] pathForResource:@"categories" ofType:@"plist"];
NSDictionary* dict = [[NSDictionary alloc] initWithContentsOfFile:path];
NSMutableArray* categories = [dict objectForKey:@"Categories"];
NSLog(@"%i", [categories count]);
// Setup the scrollview
_scrollView.delegate = self;
_scrollView.directionalLockEnabled = YES;
_scrollView.alwaysBounceVertical = YES;
_scrollView.scrollEnabled = YES;
CGRect screenRect = [[UIScreen mainScreen] bounds];
// Loop through the categories and create a BaseViewController for each one and
// store it in an array
for (int i = 0; i < [categories count]; i++) {
BaseViewController* categoryView = [[BaseViewController alloc]
initWithCategory:[categories objectAtIndex:i]];
CGRect frame = categoryView.view.frame;
frame.origin.y = screenRect.size.height * i;
categoryView.view.frame = frame;
[_scrollView addSubview:categoryView.view];
[_categoriesViews addObject:categoryView];
}
}
最佳答案
您犯了一个常见的初学者错误,即保留对 View Controller View 的引用,而不是 View Controller 本身。
您在局部变量categoryView 中创建一个BaseViewController 对象。这是一个强引用,因此该对象会保留下来。然后重复循环,创建一个新的 BaseViewController,替换categoryView 中的旧值。当您这样做时,categoryView 中不再有对先前 BaseViewController 的任何强引用,因此它被释放。
如果您希望 BaseViewController 保留下来,您需要在某处保留对它的强引用。
除此之外,你还违反了 iOS 开发的另一条规则。你永远不应该将一个 View Controller 的 View 放入另一个 View Controller 的 View 中,除非你使用 iOS 5 中添加并在 iOS 6 中扩展的父/ subview Controller 支持。文档说不要这样做。
在屏幕上混合来自多个 View Controller 的 View 会给您带来无穷无尽的问题。为了让它发挥作用,你必须做大量的内务工作,但并不是所有的内务工作都有记录。这是可能的,但如果你能够的话,你将需要花费数周的时间才能消除这些错误。另外,由于您正在做 Apple 明确禁止做的事情,因此您有责任使其正常工作,并且新的 iOS 版本很有可能会破坏您的应用程序。
关于ios - 为什么实例化后立即调用dealloc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19335403/