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

时间:2015-03-25 10:57:23

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

我在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;
        }
    });

2 个答案:

答案 0 :(得分:0)

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

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

这不是你应该如何使用视图控制器;它们应该被呈现(通常是一次一个),所以你正在做的是未定义的。

答案 1 :(得分:0)

正如@trojanfoe所说,你的设计是错误的。您无法创建视图控制器并将其视图添加到另一个视图控制器,而无需维护对视图控制器的强引用。

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

当您将视图控制器的视图添加到另一个视图控制器时,您应该使用添加到iOS的父/子视图控制器支持(在iOS 5中,如果我没记错的话。)在Xcode中进行搜索UIViewController类中的文档引用了单词&#34; parent&#34;和&#34;孩子&#34;。有一系列方法可以让你进行设置。

你需要让你的TestStepView(视图控制器?)成为DMPaletteSectionView(视图控制器?)的一个孩子吗?

BTW,停止在您的问题和代码中调用视图控制器视图。查看对象和视图控制器对象完全不同,您可以通过调用视图控制器视图来混淆自己和读者。

我在代码中使用缩写VC作为视图控制器来保持我的类名更短,同时保持它们是视图控制器,而不是视图。