我目前正在尝试使用WWDC期间介绍的有关高级NSOperations的概念。我想将使用不同class DownloadOperation : GroupOperation {
let requestContext:RequestContext
init(context:RequestContext, apiCall:API){
requestContext = context
super.init(operations: [])
name = "Generic Download"
guard let URL = apiCall.URLRequest else {
finish()
return
}
let dataTask = NSURLSession.sharedSession().dataTaskWithURL(URL) {
data, response, error in
self.downloadFinished(data, response: response as? NSHTTPURLResponse, error: error)
}
let downloadTask = URLSessionTaskOperation(task: dataTask)
let reachabilityCondition = ReachabilityCondition(host: URL)
let networkObserver = NetworkObserver()
downloadTask.addCondition(reachabilityCondition)
downloadTask.addObserver(networkObserver)
addOperation(downloadTask)
}
private func downloadFinished(data:NSData?, response:NSHTTPURLResponse?, error:NSError?){
if let data = data {
requestContext.data = data
requestContext.httpResponse = response
} else {
finishWithError(error)
}
}
}
子类(以及扩展任何类型的链接操作)的请求分开。
我使用上下文类在流程中涉及的所有操作之间共享数据(参见:Passing Data Between Two NSOperations)
class JSONUnmarshallOperation: Operation {
let context:RequestContext
init(context c:RequestContext){
self.context = c
super.init()
name = "JSON Parsing"
}
final override func execute() {
guard let data = context.data else { finish(); return }
defer {
context.data = nil
}
do {
context.JSON = try NSJSONSerialization.JSONObjectWithData(data, options: [])
finish()
} catch let error as NSError {
finishWithError(error)
}
}
}
每个子类在初始化期间获得对上下文的引用。
下载示例:
GroupOperation
JSON解析示例:
class SomeOperation: GroupOperation {
let downloadOperation:DownloadOperation
let unmarshalOperation:JSONUnmarshallOperation
init (completionHandler:<* Some Type *>) {
let blockOperation = NSBlockOperation {
//Use the callback here and access self
}
super.init(operations:[downloadOperation, unmarshalOperation, blockOperation])
}
}
我希望能够创建依赖于这两个操作的self
并定义完成回调。我想有这样的事情:
super.init
这里的问题是,在致电GroupOperation
sudo npm update npm -g
是否有一种简单而优雅的方式来添加通用完成处理程序添加{{1}}子类的结尾?
答案 0 :(得分:3)
简单的答案是,在您致电blockOperation
之后才构建super.init
:
init (completionHandler:<* Some Type *>) {
let downloadOperation = ...
let unmarshallOperation = ...
unmarshallOperation.addDependency(downloadOperation)
super.init(operations:[downloadOperation, unmarshallOperation, blockOperation])
let blockOperation = NSBlockOperation {
//Use the callback here and access self
}
blockOperation.addDependency(unmarshallOperation)
addOperation(blockOperation)
}