开发者

Adding different views to viewStack and memory management

- (void)loadQuiz:(NSInteger )quizNum {
    if([self quizViewController] != nil)
    {
        [self setQuizViewController:nil];
    }
    QuizViewController *quiz = [[QuizViewController alloc] initWithNibName:@"QuizViewController" bundle:nil];
    [quiz setUp:quizNum];
    [self setQuizViewController:quiz];
    [quiz release];

    [[self view] addSubview:[[self quizViewController]view]];
    [self setSlide1:[[[self view] subviews] objectAtIndex:0]];
    [self setSlide2:[[[self view] subviews] objectAtIndex:1]];
    [[self slide1] setHidden:NO];
    [[self slide2] setHidden:YES];
    [self performTransition];
}

In this method I'm adding subviews to my containerView. Sometimes I add an image. Sometimes I add a quiz. In another function that fires at the end of the animation I always remove the subview at the bottom of the stack so 开发者_如何学编程I never have more than 2 subViews.

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
    [[self model] setTransitioning:NO];
    [[[[self view]subviews] objectAtIndex:0] removeFromSuperview];
}

My question is do I have a memory leak building here? This seems to run fine. Thanks in advance.


It depends on whether you've set the quizViewController to retain objects assigned to it. If you do, then you've got a leak. This part looks good:

QuizViewController *quiz = [[QuizViewController alloc] initWithNibName:@"QuizViewController" bundle:nil];
[quiz setUp:quizNum];
[self setQuizViewController:quiz];
[quiz release];

But here,

if([self quizViewController] != nil)
{
    [self setQuizViewController:nil];
}

You're simply setting the quiz to nil. This means that the second time you load a quiz, the first one will get lost off in leak space. The thing to do here is either to release quizViewController, or, if you do need to hold multiple quizzes, go ahead and declare an NSMutableArray property to hold them all.

The easiest way to check for a memory leak is to go into Xcode and select "Run With Performance Tool >> Leaks" from the "Run" menu. You'll get a nice list of all leaked objects, with traces to where the leak occurred. Here's a good tutorial to get you started.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜