- (无效)dealloc问题

时间:2010-12-30 01:03:49

标签: iphone objective-c ios memory-management

您能否告诉我以下代码是否100%正确?特别是dealloc部分

FirstViewController.h

#import <UIKit/UIKit.h>
#import "SecondViewController.h"

@class SecondViewController

@interface FirstViewController : UIViewController
{
    SecondViewController   *SecondController;
}

- (IBAction)SwitchView;

@property (nonatomic, retain) IBOutlet SecondViewController *SecondController;

@end

FirstViewController.m

#import "FirstViewController.h"

@implementation FirstViewController

@synthesize SecondController;

- (IBAction)SwitchView
{    
    SecondController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
    SecondController.modalTransitionStyle = UIModalPresentationFullScreen;
    [self presentModalViewController:SecondController animated:YES];
    [SecondController release];
}

/// OTHER CODE HERE ///

- (void)dealloc
{
    [SecondController release];
    [super dealloc];
}

@end

谢谢!

2 个答案:

答案 0 :(得分:8)

不,这不对。您正在将release消息发送到dealloc中的指针,但指针可能会或可能不会指向SecondController。这可能会导致一些非常奇怪的错误,通常是随机对象被释放。

在objective-c术语中,您的类不会保留(认为“拥有”)SecondController,因此它不应该尝试在dealloc上首先释放它。

要以正确的方式声明和释放所有权,请执行以下操作:

- (IBAction)SwitchView
{    
    self.SecondController = [[[SecondViewController alloc] 
                  initWithNibName:@"SecondViewController" bundle:nil] autorelease];
    self.SecondController.modalTransitionStyle = UIModalPresentationFullScreen;
    [self presentModalViewController:self.SecondController animated:YES];
}

/// OTHER CODE HERE ///

- (void)dealloc
{
    self.SecondController = nil;
    [super dealloc];
}

这也可以保护您免受SwitchViewdealloc之间发生的任何其他事情的侵害。 (只要该内容遵循规则并使用self.SecondController = ...来更改属性)

SwitchView中,alloc / autorelease序列使您的例程保持对例程长度的所有权(稍微超出)。 self.SecondController =部分确保您的类保留SecondController对象,因为您声明了它(nonatomic,retain)

答案 1 :(得分:4)

您应该使用属性设置器来指定SecondController

我建议您仅alloc/init查看控制器一次,然后在SwitchView中显示:

#import "FirstViewController.h"

@implementation FirstViewController

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
   if((self = [super initWithNibName:nibName bundle:nibBundle])) {
      self.SecondController = [[[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil] autorelease];
      SecondController.modalTransitionStyle = UIModalPresentationFullScreen;
   }
   return self;
}

- (IBAction)SwitchView
{    
    [self presentModalViewController:SecondController animated:YES];
}

/// OTHER CODE HERE ///

- (void)dealloc
{
    [SecondController release];
    [super dealloc];
}

@end

这样,您实际上只创建了一次SecondController视图控制器,而不是每次调用-SwitchView时都创建它。