我在UIView中有一行UILabel文本,它通過NSTimer定期更新。這段代碼應該每隔一段時間在屏幕底部附近寫一個狀態項。數據來自其控制之外。UIView和NSTimer不釋放內存
我的應用程序運行速度非常快,因爲它看起來UILabel沒有被釋放。看來dealloc從來沒有被調用過。
這裏是我的代碼非常壓縮版本(錯誤檢查等爲清楚起見移除。):
文件:SbarLeakAppDelegate.h
#import <UIKit/UIKit.h>
#import "Status.h"
@interface SbarLeakAppDelegate : NSObject
{
UIWindow *window;
Model *model;
}
@end
文件:SbarLeakAppDelegate.m
#import "SbarLeakAppDelegate.h"
@implementation SbarLeakAppDelegate
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
model=[Model sharedModel];
Status * st=[[Status alloc] initWithFrame:CGRectMake(0.0, 420.0, 320.0, 12.0)];
[window addSubview:st];
[st release];
[window makeKeyAndVisible];
}
- (void)dealloc
{
[window release];
[super dealloc];
}
@end
File:Status.h
#import <UIKit/UIKit.h>
#import "Model.h"
@interface Status : UIView
{
Model *model;
UILabel * title;
}
@end
File:Status.m 這是問題出在哪裏。 UILabel似乎沒有被釋放,並且很可能還有字符串。
#import "Status.h"
@implementation Status
- (id)initWithFrame:(CGRect)frame
{
self=[super initWithFrame:frame];
model=[Model sharedModel];
[NSTimer scheduledTimerWithTimeInterval:.200 target:self selector:@selector(setNeedsDisplay) userInfo:nil repeats:YES];
return self;
}
- (void)drawRect:(CGRect)rect
{
title =[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 12.0f)];
title.text = [NSString stringWithFormat:@"Tick %d", [model n]] ;
[self addSubview:title];
[title release];
}
- (void)dealloc
{
[super dealloc];
}
@end
文件:Model.h(今年及未來的數據源,所以僅包括完整。)它所做的就是更新一個計數器每秒。
#import <Foundation/Foundation.h>
@interface Model : NSObject
{
int n;
}
@property int n;
+(Model *) sharedModel;
-(void) inc;
@end
文件:Model.m
#import "Model.h"
@implementation Model
static Model * sharedModel = nil;
+ (Model *) sharedModel
{
if (sharedModel == nil)
sharedModel = [[self alloc] init];
return sharedModel;
}
@synthesize n;
-(id) init
{
self=[super init];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(inc) userInfo:nil repeats:YES];
return self;
}
-(void) inc
{
n++;
}
@end
非常感謝。這似乎已經成功了。我將title = [[UILabel alloc] ....行移至init部分。 – 2009-07-17 11:33:23