在NSOperation中取消NSData initWithContentsOfURL

bre*_*dan 1 nsoperation nsdata ios

我目前在NSOperation中有以下代码,它有一个keyPath"isCancelled"的观察者:

    downloaded = FALSE;
    NSURL *url = [NSURL URLWithString:requestString];
    dataXML = [[NSData alloc] initWithContentsOfURL:url];
    downloaded = TRUE;
Run Code Online (Sandbox Code Playgroud)

我想这样做,以便observeValueForKeyPath函数能够取消dataXML继续或只是在NSOperation发送取消消息后完全停止NSOperation.NSOperation的取消操作取消仅通知操作它应该停止,但不会强制我的操作代码停止.

Nic*_*ood 7

你无法取消它.

如果您希望能够在中途取消加载,请使用NSURLConnection异步模式下的操作.设置还需要更多工作,但您可以在下载过程中的任何时候取消.

或者,您可以使用我编写的这个方便的类NSURLConnection,它在单个方法调用中包装异步及其委托;-)

NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[RequestQueue mainQueue] addRequest:request completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    if (data && error == nil)
    {
        //do something with your downloaded data
    }
}];

//to cancel the download at any time, just say
[[RequestQueue mainQueue] cancelRequest:request];
Run Code Online (Sandbox Code Playgroud)

简单!

</shamelessSelfPromotion>

请注意,上面的请求已经是异步的,并且该类已经管理了多个请求的排队,因此您不需要(也不应该)将其包装在一个NSOperationQueue.