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)
谢谢!
不,这不正确.您正在将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 = ...
更改属性)
在SwitchView
中alloc
/ autorelease
顺序,使您的日常保留所有权的程序的长度(和一点点超越).该self.SecondController =
部分确保您的类保留该SecondController
对象,因为您声明了它(nonatomic,retain)
.
归档时间: |
|
查看次数: |
555 次 |
最近记录: |