取消已经释放的对象中的块请求
问题描述:
因此我使用AFNetworking与Web服务进行异步请求。取消已经释放的对象中的块请求
AFJSONRequestOperation *operation = [AFJSONRequestOperation operationWithRequest:request success:^(id JSON)
{
[self doSomeStuff];
} failure:^(NSHTTPURLResponse *response, NSError *error)
{
XLog("%@", error);
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
现在当了“自我”的对象dealloced之前完成的请求,会发生什么的当然[self doSomeStuff];
我的申请chrashes。
有没有办法取消这个块请求释放我的对象?
答
我做了一些示例代码,结果可能会对您感兴趣。
我创建的创建,就像你的请求的类:
@implementation Aftest
@synthesize name = _name;
- (void) doSomeStuff
{
NSLog(@"Got here %@", self.name);
}
- (void)startDownload
{
self.name = [NSString stringWithFormat:@"name"];
NSURL *requestURL = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2"];
NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];
AFJSONRequestOperation *operation = [AFJSONRequestOperation operationWithRequest:request success:^(id JSON)
{
[self doSomeStuff];
} failure:^(NSHTTPURLResponse *response, NSError *error)
{
NSLog(@"%@", [error localizedDescription]);
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
}
@end
而且与所谓的:
Aftest *af = [[Aftest alloc] init];
NSLog(@"1 - retain count %d", [af retainCount]);
[af startDownload];
NSLog(@"2 - retain count %d", [af retainCount]);
[af release];
NSLog(@"3 - retain count %d", [af retainCount]);
,我得到的结果是:
2011-10-09 09:28:41.415 aftes[6154:f203] 1 - retain count 1
2011-10-09 09:28:41.418 aftes[6154:f203] 2 - retain count 2
2011-10-09 09:28:41.419 aftes[6154:f203] 3 - retain count 1
2011-10-09 09:28:43.361 aftes[6154:f203] Got here name
你对象应该在块内传递时保留。它应该避免这些崩溃。
无论哪种方式,正如Micheal回答的那样,只要您有权访问操作对象,就应该可以调用cancel
。
答
据我所见,您应该能够拨打cancel
停止操作。
你是对的。我在我的完整块中使用了一个类,我只将它分配给我的对象,此块位于此处。保留这个类并在dealloc上释放它现在工作正常。谢谢! – choise
请注意,retainCount永远不能返回0,并且不能用于证明对象在任何给定的持续时间内都保持可用。 – bbum