[ios]-(void) dealloc 问题

发布时间: 2017/3/21 23:13:14
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

你能告诉我,是否下面的代码是 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

谢谢你 !

解决方法 1:

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

在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)

赞助商