使用手动内存管理。以下代码运行良好,没有发生崩溃。但是没有-(void)dealloc
办法。这段代码错了吗?我应该添加-(void)dealloc
吗?
我的类.h
#import <UIKit/UIKit.h>
@interface MyClass : NSObject {
@private
BOOL flag;
UIView *view;
UILabel *label;
UIButton *button;
UITabBar *tabBar;
UIWebView *webView;
UIImageView *imageView;
}
@property (nonatomic, retain) UIView *view;
@property (nonatomic, retain) UILabel *label;
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) UITabBar *tabBar;
@property (nonatomic, retain) UIWebView *webView;
@end
我的班级.m
#import "MyClass.h"
@implementation MyClass
@synthesize view;
@synthesize label;
@synthesize button;
@synthesize tabBar;
@synthesize webView;
- (id)init {
self = [super init];
if (self) {
// Initialization code
// Among other code,
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
}
return self;
}
// Other methods here.
// But -(void)dealloc is not overridden here in the MyClass.m
@end
如果我们必须-(void)dealloc
为上面的代码添加,应该是这样的:
覆盖 -(void)dealloc
-(void)dealloc {
[view release];
[label release];
[button release];
[tabBar release];
[webView release];
[super dealloc];
}
更新 1
@synthesize 添加,见上文。
更新 2
没有把它放到另一个帖子中,因为这似乎是相当相关的问题:
见上面MyClass.m/.h
,有一个私有的ivar(这里不知道应该叫ivar还是字段)UIImageView *imageView;
,它没有属性,没有@synthesize
,那里给出了初始化,我们怎样才能dealloc呢?也在? [imageView release];
_-(void)dealloc
更新 3
我们必须在发布 ivars 之前检查可用性吗?也就是说,而不是[view release];
,使用这个:
if (nil != view) {
[view release];
}