gpt4 book ai didi

ios - 为什么取消 AFHTTPRequestOperation 有时会遇到成功 block ?

转载 作者:可可西里 更新时间:2023-11-01 03:34:29 26 4
gpt4 key购买 nike

我正在通过 Google Places API 在搜索栏上集成自动完成功能。对于网络请求,我使用 AFNetworking。

我想一次只运行一个请求。所以每次我输入一个新字母时,我都会执行以下操作:

1 - 取消之前的AFHTTPRequestOperation:

[self.currentGlobalSearchListRequest cancel];
NSLog(@"%@ cancelled", self.currentGlobalSearchListRequest);

2 - 启动一个新的 AFHTTPRequestOperation:

self.currentGlobalSearchListRequest = [searchService getGlobalSearchListItemsForString:searchString inRegion:region delegate:self];
NSLog(@"%@ started", self.currentGlobalSearchListRequest);

这是请求完成运行时调用的回调:

- (void)request:(PointSearchRequest *)request didLoadSearchListItems:(NSArray *)searchListItems {
NSAssert(request == self.currentGlobalSearchListRequest, @"!!!callback from a request that should be cancelled!!!");
[self.delegate searchListLoader:self didLoadGlobalSearchList:searchListItems];
}

有时我会遇到断言,所以我调查了一下,发现大多数时候调用失败 block 时会出现错误代码 NSURLErrorCancelled,这是预期的行为,但有时会调用成功 block !

这个堆栈跟踪告诉我代码中的事情以正确的顺序发生

2013-12-22 09:38:46.484 Point[63595:a0b] <PointSearchRequest: 0x18202b50> started
2013-12-22 09:38:46.486 Point[63595:a0b] <PointSearchRequest: 0x18202b50> cancelled
2013-12-22 09:38:46.487 Point[63595:a0b] <PointSearchRequest: 0x181a5dd0> started
2013-12-22 09:38:46.496 Point[63595:a0b] *** Assertion failure in -[SearchListLoader request:didLoadSearchListItems:], /Users/aurelienporte/Documents/Developpement/Perso/iOS/Point/Point/Classes/Models/SearchListLoader.m:82
(lldb) po request
<PointSearchRequest: 0x18202b50>

另外,当成功 block 被调用时,我查看了 AFHTTPRequestOperation 上的属性 isCancelled 但它没有给我(!!!)我知道我最终可能只是测试而不是使用 NSAssert,但我想找到问题的根源。

你有没有遇到过类似的cancel并没有真正取消请求的问题?然后调用成功 block 而不是失败 block ?这是要向 AFNetworking 团队报告的问题吗?谢谢!

如果它有帮助的话,请求会非常快(谷歌自动完成 API 令人印象深刻......)

最佳答案

查看 AFNetworkingCode,请参阅 AFURLConnectionOperation.m, line 461

- (void)cancel {
[self.lock lock];
if (![self isFinished] && ![self isCancelled]) {
[super cancel];

if ([self isExecuting]) {
[self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
}
}
[self.lock unlock];
}

似乎您看到的竞争条件的唯一可能性是操作已经完成时的情况 ([self isFinished])。请注意,您的取消 和完成 block 之间的间隔非常小(10 毫秒)。也许您可以在尝试取消请求之前检查 isFinished

关于ios - 为什么取消 AFHTTPRequestOperation 有时会遇到成功 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20727949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com