你能告诉我以下代码是否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;
@endFirstViewController.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谢谢!
发布于 2010-12-30 01:15:29
不不对。您将release消息发送到dealloc中的指针,但是指针可能指向SecondController,也可能不再指向SecondController。这可能会导致一些非常奇怪的错误,通常是随机对象被释放。
在objective术语中,您的类不保留(考虑“属于”) 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];
}这还将保护您免受SwitchView和dealloc之间发生的任何其他事情的影响。(只要这些内容遵循规则,并使用self.SecondController = ...更改属性)
在SwitchView中,alloc/autorelease序列使您的例程保留例程长度的所有权(并且稍微超出)。self.SecondController =部件确保类保留了SecondController对象,因为您声明了它为(nonatomic,retain)。
发布于 2010-12-30 01:07:51
您应该使用属性设置器来分配SecondController。
我建议您只使用alloc/init视图控制器一次,然后在SwitchView中显示它:
#import "FirstViewController.h"
@implementation FirstViewController
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
if((self = [super initWithNibName:nibName bundle:nibBundle])) {
self.SecondController = [[[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil] autorelease];
SecondController.modalTransitionStyle = UIModalPresentationFullScreen;
}
return self;
}
- (IBAction)SwitchView
{
[self presentModalViewController:SecondController animated:YES];
}
/// OTHER CODE HERE ///
- (void)dealloc
{
[SecondController release];
[super dealloc];
}
@end这样,您实际上只创建SecondController视图控制器一次,而不是每次调用-SwitchView时都创建它。
https://stackoverflow.com/questions/4559221
复制相似问题