在方法范围中释放“引用”变量

时间:2010-02-03 05:31:39

标签: objective-c iphone cocoa-touch xcode

在objective-c(可可触摸)中,我有一系列我正在切换的UIViewControllers。

- (void)switchViews:(id)sender
{
    UIButton *button = (UIButton *)sender;
    UIViewController *nextViewController;
    int tag = button.tag;

    switch (tag)
    {
        // -- has already been created
        case kFinancialButton:
            nextViewController = financials;
            break;

        case kSocialButton:
            if (social == nil)
            {
                SocialViewController *socialViewController = [[SocialViewController alloc] initWithNibName:@"SocialViewController" bundle:nil];
                social = socialViewController;
                [socialViewController release];
            }
            nextViewController = social;
            break;

        case kTicketingButton:
            if (ticketing == nil)
            { 
                TicketingViewController *ticketingViewController = [[TicketingViewController alloc] initWithNibName:@"TicketingViewController" bundle:nil];
                ticketing = ticketingViewController;
                [ticketingViewController release];
            }
            nextViewController = ticketing;
            break;
    }

        ///////
------> // -- [button/nextViewController release]????
        ///////

    [self setActiveButton:button];
}

如您所见,我将其中一个视图控制器分配给“nextViewController”。我想知道的是,如果我需要释放这个“本地”变量,或者是否可以单独留下,因为它只是指向我的一个视图控制器(我在dealloc中发布)。我不认为“标签”需要发布,因为它是“原始的”,对吗?按钮怎么样?我不太明白应该和不应该明确地发布什么,所以也许我会过于谨慎。提前谢谢。

1 个答案:

答案 0 :(得分:1)

一般情况下,您只需要release一个retain'd init'或copy'd的变量。

编辑:

稍微阅读一下你的代码后,似乎你还有其他问题与坏的价值观。下面的代码对我来说更有意义。这假设财务,社交和票务都是@synthesized ivars。

- (void)switchViews:(id)sender
{
    UIButton *button = (UIButton *)sender;
    UIViewController *nextViewController;
    int tag = button.tag;

    switch (tag)
    {
        // -- has already been created
        case kFinancialButton:
            nextViewController = self.financials;
            break;

        case kSocialButton:
            if (!social) {
                self.social = [[[SocialViewController alloc] initWithNibName:@"SocialViewController" bundle:nil] autorelease];
            }
            nextViewController = self.social;
            break;

        case kTicketingButton:
            if (!ticketing) {
                self.ticketing = [[[TicketingViewController alloc] initWithNibName:@"TicketingViewController" bundle:nil] autorelease];
            }
            nextViewController = self.ticketing;
            break;
    }

    // Do something with nextViewController I'd assume

    [self setActiveButton:button];
}