iphone初学者:无法弄清楚泄漏的位置

时间:2011-03-06 23:06:48

标签: iphone uiview uilabel memory-leaks instruments

我正在努力开发一些iphone。为了更好地理解事物,我首先没有IB。

我设法构建了一个显示一些文本的基本应用程序。没什么大不了的,直到我通过仪器运行它。它向我展示了一些泄漏,我无法理解它们。

对此的任何帮助将不胜感激。

MyAppDelegate.h

@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow            *window;
    MyViewController    *viewController;
}

@property (nonatomic, retain)  IBOutlet UIWindow *window;
@property (nonatomic, retain)  MyViewController *viewController;

@end

MyAppDelegate.m

@implementation MyAppDelegate

@synthesize window;
@synthesize viewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    // NEXT LINE LEAKS   
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
}
- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}
@end

MyViewController.h

@interface MyViewController : UIViewController {
    UILabel     *firstMessage;
}

MyViewController.m

-(void)loadView {

    // Background
    CGRect mainFrame = [[UIScreen mainScreen] applicationFrame];
    UIView *contentView = [[UIView alloc] initWithFrame:mainFrame];
    contentView.backgroundColor = [UIColor blackColor];
    self.view = contentView;
    [contentView release];

    // Add UILabel
    // NEXT LINE LEAKS   
    firstMessage = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30)];
    firstMessage.font = [UIFont fontWithName:@"Helvetica" size:16];
    firstMessage.textColor = [UIColor whiteColor];
    firstMessage.backgroundColor = [UIColor blackColor]; 
    [self.view addSubview:firstMessage];
    [firstMessage release];
 }

-(void) viewDidLoad {
    NSString * msg;
    msg=[[NSString alloc] initWithFormat:@"stuff here"];
    firstMessage.text=msg;
    [msg release];
}

-(void)dealloc {
    [firstMessage release];
    [super dealloc];
}

2 个答案:

答案 0 :(得分:1)

尝试在标题@property (nonatomic, retain) UILabel* firstMessage中使用@synthesize firstMessage,然后在dealloc方法中释放firstMessage对象。

答案 1 :(得分:0)

尽量不要在loadView中发布firstMessage。只能在控制器的dealloc方法中释放它。