iphone - -(void)取消分配问题

标签 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

谢谢!

最佳答案

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

关于iphone - -(void)取消分配问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4559221/

相关文章:

javascript - 使用 CPU 速度从 Javascript 检测 iPhone 5 设备

javascript - 在 iOS Safari 中单击会在您点击的下方的元素上触发 "hover state"

ios - 无法找到目标 'IQKeyboardManagerSwift' 的模块 'armv7-apple-ios' ;

ios - 如何在iOS中集成whatsapp

ios - 如何将TextField的内容保存到plist

ios - 预填充的静态数据,以在我的 iOS 应用程序中发布

iphone - iOS 以编程方式检查调用转移是否处于事件状态

iphone - 在 iOS 6 中使用格式输入 UITextView

iphone - 为 .h 文件 iphonesdk 禁用 ARC

ios - Objective-C:将大多数消息转发给另一个对象(在运行时)