【问题标题】:Custom object of same type added multiple times inside for loop在 for 循环中多次添加相同类型的自定义对象
【发布时间】:2015-03-25 10:57:22
【问题描述】:

我在 for- 循环中分配自定义对象(本例中为视图控制器)。一切似乎都很好。但是当我点击 viewcontroller 的第一个自定义对象的按钮时,应用程序崩溃了。 这是因为未保留自定义对象的实例。虽然它适用于最后添加的对象。 请指教。

    dispatch_async(dispatch_get_main_queue(), ^{
        NSInteger index = 0;
        for (TestStep *obj_Teststep in objTestSuite.testSteps) {
            TestStepView * obj_TestStepView = [[TestStepView alloc] initWithNibName:@"TestStepView" bundle:[NSBundle mainBundle]];
            obj_TestStepView.testStep = obj_Teststep;
            obj_TestStepView.delegate = self;
            DMPaletteSectionView *sectionView = [[DMPaletteSectionView alloc] initWithContentView:obj_TestStepView.view andTitle:[NSString stringWithFormat:@"Test Step %@ - %@",obj_Teststep.executionOrder,obj_Teststep.apiCallPath] initialState:DMPaletteStateCollapsed withAction:YES andIndex:index];
            sectionView.layer.backgroundColor = [NSColor redColor].CGColor;
            [sectionArray addObject:sectionView];
            index++;
        }
        [sectionArray addObject:[[DMPaletteSectionView alloc] initWithContentView:self.addNewTestStepView andTitle:@"Add Test Step" initialState:DMPaletteStateExpanded withAction:NO andIndex:0]];
        container.sectionViews = sectionArray;

        for (int i =0; i<container.sectionViews.count; i++) {
            DMPaletteSectionView *dmobj = [container.sectionViews objectAtIndex:i];
            dmobj.delegate = self;
        }
    });

【问题讨论】:

    标签: ios objective-c cocoa memory-management retain


    【解决方案1】:

    正如@trojanfoe 所说,您的设计有问题。如果不维护对视图控制器的强引用,则无法创建视图控制器并将其视图添加到另一个视图控制器。

    您创建了一堆 TestStepView 对象(我假设它们是视图控制器?)然后您将这些对象的视图传递给 DMPaletteSectionView,但永远不要保留对 TestStepView 对象的强引用。那是行不通的。

    当您将视图控制器的视图添加到另一个视图控制器时,您应该使用添加到 iOS 的父/子视图控制器支持(如果我没记错的话,在 iOS 5 中。)在 UIViewController 中的 Xcode 文档中进行搜索“父”和“子”这两个词的类参考。有一系列方法可以让您进行设置。

    您需要让您的 TestStepView(视图控制器?)成为 DMPaletteSectionView(视图控制器?)的子级

    顺便说一句,停止在您的问题和代码中调用视图控制器视图。视图对象和视图控制器对象是完全不同的,调用视图控制器视图会使您自己和您的读者感到困惑。

    我在代码中使用缩写 VC 来表示视图控制器,以使我的类名更短,同时清楚地表明它们是视图控制器,而不是视图。

    【讨论】:

      【解决方案2】:

      您正在分配视图控制器,然后将它们有效地丢弃,因为 ARC 会在它们超出范围时释放它们:

      for (TestStep *obj_Teststep in objTestSuite.testSteps) {
          TestStepView * obj_TestStepView = [[TestStepView alloc] initWithNibName:@"TestStepView"
                                                                           bundle:[NSBundle mainBundle]];
          // ...
          // ARC will deallocate obj_TestStepView here
      }
      

      这不是您应该使用视图控制器的方式;它们应该被呈现(通常一次一个),所以你正在做的事情是不确定的。

      【讨论】:

      • 有没有办法解决这个问题,因为我只需要这样。
      • @JasmeetSingh 您需要一次性生成大量视图控制器吗?为什么?用户一次只能使用一个视图。
      猜你喜欢
      • 2020-03-05
      • 1970-01-01
      • 2023-04-08
      • 2021-05-05
      • 2013-01-31
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      相关资源
      最近更新 更多