在viewDidLoad中使用init并在viewDidUnload中释放的iOS内存问题

时间:2011-09-21 13:57:05

标签: ios

以下代码是否存在潜在的内存问题?:

- (void)viewDidLoad
{ 
    locationManager = [[CLLocationManager alloc] init];
}

- (void)viewWillAppear:(BOOL)animated {

    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
}

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

我已经用仪器检查了它,它说上面的代码有内存泄漏。

2 个答案:

答案 0 :(得分:5)

您应该在dealloc方法中释放locationManager。

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

原因是viewDidUnload无法保证被调用。

有关详细信息,请参阅以下问题:

When is UIViewController viewDidUnload called?

viewdidunload is not getting called at all!

答案 1 :(得分:0)

除此之外看起来相当不错:

  1. viewDidLoad添加[super viewDidLoad];
  2. 之初
  3. viewWillAppear:添加[super viewWillAppear:animated];
  4. 之初