开发者

iOS memory issue with init in viewDidLoad and release in viewDidUnload

Are there any potential memory issues with the following code?:

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

- (void)viewWillAp开发者_Python百科pear:(BOOL)animated {

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

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

I have checked it with Instrument and it says there is memory leaking with above code.


You should release the locationManager in the dealloc method.

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

The reason for that is that viewDidUnload is not guaranteed to get called.

For details see these questions:

When is UIViewController viewDidUnload called?

viewdidunload is not getting called at all!


It looks quite well besides:

  1. At the beginning of viewDidLoad add [super viewDidLoad];.
  2. At the beginning of viewWillAppear: add [super viewWillAppear:animated];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜