gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:18:59 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com