1
我目前正在嘗試使用WWDC期間介紹的有關Advanced NSOperations的概念。我想分開使用不同Operation
子類(以及任何類型的鏈式操作)的請求過程。高級NSOperations,GroupOperation的回調
我使用上下文類共享所有參與這一過程的操作之間的數據(見:Passing Data Between Two NSOperations)initalization期間
class RequestContext {
var httpResponse:NSHTTPURLResponse?
var data:NSData?
var JSON:AnyObject?
}
每個子類去上下文的參考。
例下載:
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)
}
}
}
例JSON解析:
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
依靠這兩種操作並定義一個完成回調。我想有這樣的事情:
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])
}
}
這裏的問題是,我會打電話super.init
之前訪問self
是否有一個簡單而優雅的方式來增加一個通用完成處理程序添加結束GroupOperation
的子類?