您能告诉我以下代码是否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

谢谢!

最佳答案

不,这是不正确的。您正在将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)

08-19 11:53