我想弄清楚以下情况推荐的做法是什么.某些对象(如CLLocationManager或MKReverseGeocoder)将其结果异步发送到委托回调方法.可以在回调方法中释放CLLocationManager或MKReverseGeocoder实例(或者它可能是什么类)吗?关键是你不再需要那个对象,所以你告诉它停止发送更新,将其委托设置为nil,然后释放对象.
伪代码:
@interface SomeClass <CLLocationManagerDelegate>
...
@end
@implementation SomeClass
...
- (void)someMethod
{
CLLocationManager* locManager = [[CLLocationManager alloc] init];
locManager.delegate = self;
[locManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// Do something with the location
// ...
[manager stopUpdatingLocation];
manager.delegate = nil;
[manager release];
}
@end
Run Code Online (Sandbox Code Playgroud)
我想知道这种使用模式是否被认为总是好的,如果它被认为永远不行,或者它是否取决于类?
有一个明显的情况是释放委托对象会出错,即如果它在通知委托后需要做的事情.如果委托释放对象,则其内存可能会被覆盖并且应用程序崩溃.(这似乎是我的应用程序在特定环境中使用CLLocationManager时发生的情况,仅在模拟器上.我试图弄清楚它是否是模拟器错误或者我正在做的事情是否存在根本缺陷.)
我一直在寻找,我无法找到一个确定的答案.有没有人有权威的来源可以回答这个问题?