- (无效)dealloc问题

Alu*_*num 1 iphone memory-management objective-c ios

你能告诉我以下代码是否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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

谢谢!

mvd*_*vds 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];
}
Run Code Online (Sandbox Code Playgroud)

这也可以保护你免受在SwitchView和之间发生的任何其他事情dealloc.(只要这些东西遵循规则并用于self.SecondController = ...更改属性)

SwitchViewalloc/ autorelease顺序,使您的日常保留所有权的程序的长度(和一点点超越).该self.SecondController =部分确保您的类保留该SecondController对象,因为您声明了它(nonatomic,retain).