ios - 为什么实例化后立即调用dealloc?

标签 ios objective-c arrays uiviewcontroller 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];
  }

}

最佳答案

您犯了一个常见的初学者错误,即保留对 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/

相关文章:

c - c 中的结构数组 : giving all the strings same values (with the int it works well). 我该怎么办?

iphone - 这是从后台线程访问 UI 工具包的安全方法吗...?

ios - 为什么当我在 iPhone 6+ 上旋转时,我的导航栏从我的 Split View中消失了?

iphone - 如何避免从照片库中选择或从 ios 中的相机捕获的图像的背景?

objective-c - 在应用程序启动时执行某些操作?

c - 处理数组越界或负数组索引的最佳方法

ios - 重新加载部分时 tableview 标题 uiview 消失

javascript - 每次我单击自动填充按钮时,它都会在字段中返回 "nil",而不是保存的字符串

ios - 使用它的 indexPath.row 更改单元格图像

c - 关于C中数组相等的问题