iOS内存泄漏,自定义TabBar失控分配视图控制器

时间:2013-12-30 02:54:36

标签: ios objective-c memory-leaks uiviewcontroller

我使用以下代码在两个标签之间切换:

-(void)switchPage:(UIButton *)sender{


    DLog(@"");
    DLog(@"child view controllers %lu", (unsigned long)self.childViewControllers.count);


    switch(sender.tag){
        case 0:{

            for(id object in self.childViewControllers){

                if([object isKindOfClass:[QuestionsVC class]]){


                    [questionsTab willMoveToParentViewController:nil];
                    [questionsTab.view removeFromSuperview];
                    [questionsTab removeFromParentViewController];
                    questionsTab = nil;

                }

            }

            questionsTab = [[QuestionsVC alloc] init];
            [self addChildViewController:questionsTab];
            [self.view addSubview: questionsTab.view];
            [questionsTab didMoveToParentViewController:self];
            [self.view bringSubviewToFront:tabBarView];
            [self drawGrayLineLayer];

            break;
        }

        case 1:{


            for(id object in self.childViewControllers){

                if([object isKindOfClass:[AnswersVC class]]){

                    [answersTab willMoveToParentViewController:nil];
                    [answersTab.view removeFromSuperview];
                    [answersTab removeFromParentViewController];
                    answersTab = nil;

                }

            }

            answersTab = [[AnswersVC alloc] init];
            [self addChildViewController:answersTab];
            [self.view addSubview: answersTab.view];
            [answersTab didMoveToParentViewController:self];
            [self.view bringSubviewToFront:tabBarView];
            [self drawGrayLineLayer];

            break;
        }

}

奇怪的是,根视图控制器(标签栏)的childVCs数量保持不变,而没有释放任何子视图控制器。

有什么问题?

下面是一个乐器快照,告诉我每次代码运行时都会重新分配每个视图控制器,旧的视图控制器不会被解除分配。

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

我遇到的问题是我从子视图控制器初始化了其他对象,然后有一个委托属性,并且该委托是strong所以对象保留了它的父对象 - 委托 - viewcontrolller,创建了保留周期。

代表应该几乎总是weak(或几乎从不strong)我所学的