OGeek|极客世界-中国程序员成长平台

标题: ios - 为什么在实例化后立即调用dealloc? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 04:37
标题: ios - 为什么在实例化后立即调用dealloc?

在循环内实例化之后调用 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];
  }

}



Best Answer-推荐答案


您犯了一个常见的初学者错误,即保留对 View Controller View 的引用,而不是 View Controller 本身。

您在局部变量 categoryView 中创建一个 BaseViewController 对象。这是一个强引用,所以对象被保留。然后循环重复,您创建一个新的 BaseViewController,替换 categoryView 中的旧值。当您这样做时,不再有对 categoryView 中先前 BaseViewController 的任何强引用,因此它会被释放。

如果您希望 BaseViewController 继续存在,您需要在某处保持对它的强引用。

除此之外,您还打破了 iOS 开发的另一条规则。除非您使用在 iOS 5 中添加并在 iOS 6 中扩展的父/ subview Controller 支持,否则您永远不应该将一个 View Controller 的 View 放在另一个 View Controller 中。文档说不要这样做。

在屏幕上混合来自多个 View Controller 的 View 会给您带来无穷无尽的问题。为了使其正常工作,您必须进行大量的内务处理,而且并非所有的内务处理都被记录在案。它可能,但如果可以的话,您将花费数周时间来消除这些错误。此外,由于您正在做 Apple 明确表示不应该做的事情,因此您有责任使其正常工作,并且新的 iOS 版本可能会破坏您的应用程序。

关于ios - 为什么在实例化后立即调用dealloc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19335403/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4