在 for 循环中多次添加相同类型的自定义对象

Custom object of same type added multiple times inside for loop

我正在 for 循环内分配自定义对象(在本例中为 viewcontroller)。一切似乎都很好。但是当我点击 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;
        }
    });

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

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

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

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

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

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

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

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

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