【问题标题】:using custom init method in iphone -identifying a leak在 iphone 中使用自定义 init 方法 - 识别泄漏
【发布时间】:2026-01-10 10:55:01
【问题描述】:

对于我的一个自定义类,我定义了一个名为 initialize 的方法,用于在初始化的同时设置一些实例变量。代码如下。分析器工具报告 viewDidLoad 中的泄漏与 [[Employee alloc].. 由于我在 dealloc 中释放变量,我认为这应该没问题..可能是什么问题?提前致谢。

@interface testViewController : UIViewController <UITextFieldDelegate>{
    Employee *employee;
}
- (void)viewDidLoad {  
if(employee ==nil) 
   employee = [[Employee alloc] initialize:@"John"];    

if (![employee.entityName isEqualToString:@"Test"]) { //The leak is reported here for object allocated above
    ///...
}

}

- (void)viewDidUnload {
    [super viewDidUnload];
    employee = nil;
}

- (void)dealloc {
    [super dealloc];
  [employee release];

}

//In the Employee class
-(id) initialize:(NSString*) name{
    self = [super init];

    self.entityName = name;


    return self;
}

【问题讨论】:

    标签: iphone memory-leaks init


    【解决方案1】:

    在您的viewDidUnLoad 中,您需要先将release 员工设置为nil。否则在您的dealloc 中,您只是在释放nil

    - (void)viewDidUnload {
        [super viewDidUnload];
        [employee release];
        employee = nil;
    }
    

    【讨论】:

    • 嗨,谢谢,但我仍然无法删除报告的泄漏。想知道为什么:(