我有一个我调用的远程服务,它异步处理请求。返回数据后,我将刷新我的本地 UI。
但有时当 View 消失并且异步调用仍在队列中时,应用程序会因错误 EXEC BAD ACCESS
崩溃(即对象已被释放),即
My app crashes when the service returns but the ViewController is disposed.
主要是在 View Controller 不再存在之后调用
[delegate respondsToSelector:@selector (methodName:)]
时出现错误。可能我需要在
viewWillDisappear
中取消我所有的异步调用(正在运行或在队列中等待)。但我无法取消正在运行的通话。我已经尝试过 this 但在
viewWillDisappear
我的 self.navigationController.delegate
已经为零。编辑:
调用服务的方法:
{
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@“%@method_name”,Base_URL]]];
[request setRequestMethod:@"POST"];
[request setTimeOutSeconds:600];
[request setPostValue:userID forKey:@“id”];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestFinished:)];
[request setDidFailSelector:@selector(requestFailed:)];
[request startAsynchronous];
}];
[operationQueue addOperation:operation];
}
还有我的
requestFinished
方法(我的应用程序崩溃的地方)-(void)requestFinished:(ASIHTTPRequest *)request
{
// some stuff
// It's working fine when I normally run my app but fails when I rapidly changes the View Controller.
if ([delegate respondsToSelector:@selector(gotResponseData:)]) // Here my app crashes
{
[delegate gotResponseData:responseDict];
}
}
.h 文件中的委托(delegate)属性:
@property (nonatomic,assign)id <protocolName>delegate;
主要是当我在 View Controller 之间快速切换时,这个应用程序崩溃了。
如果需要,我会编辑我的问题。
请给我一些指导。
最佳答案
在您的 block 操作中,您应该使用对 self 的弱引用,以便如果/当 self 被释放时,该操作不会调用无效引用。
实际上,您实际上并不需要该操作,因为无论如何您都在操作内部启动异步进程。
您在 self 中的委托(delegate)属性也应该很弱,因为您的代码表明问题是委托(delegate)使用了不安全的未保留方法(因为您说崩溃发生的位置)。
通常,您只会有一个从 self 运行的请求,因此您应该维护对请求的引用并在 self 被销毁时取消它。
关于ios - 如果 View Controller 不再存在,则在异步调用中出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27827345/