我用this指南使我的应用程序使用NSOperationQueue和NSOperations。但是我的代码仍然在主线程上运行,不管:S?我必须说我是NSOperation的新手,我认为这是我错过的一件小事。在主线程上运行NSOperation
class CountryFetcher: NSObject{
var operation: NSOperation?
var alamoFireQueue: NSOperationQueue{
let val = NSOperationQueue()
val.maxConcurrentOperationCount = 10
val.name = "Alamofire Downloading Queue"
return val
}
func getCountries(){
operation = CountryProcessor(URLString: (BASE_URL + "countries/"+CAT_STAMPS))
alamoFireQueue.addOperation(operation!)
}
}
class CountryProcessor : ConcurrentOperation {
let URLString: String
weak var request: Alamofire.Request?
init(URLString: String) {
self.URLString = URLString
super.init()
}
override func main() {
request = Alamofire.request(.GET, URLString).responseJSON { response in
if let dataResponse = response.data{
var test: NSArray?
do{
test = try NSJSONSerialization.JSONObjectWithData(dataResponse, options: NSJSONReadingOptions()) as! NSArray
}catch let error as NSError{
print(error.localizedDescription)
}
for _ in 1...100{
NSLog("main thread? %@", NSThread.isMainThread() ? "YES" : "NO");
}
}
self.completeOperation()
}
}
override func cancel() {
request?.cancel()
super.cancel()
}
}
这是ConcurrentOperation类。我在上面的链接中从帖子中复制了它。
class ConcurrentOperation : NSOperation {
override var asynchronous: Bool {
return true
}
override var concurrent: Bool{
return true
}
private var _executing: Bool = false
override var executing: Bool {
get {
return _executing
}
set {
if (_executing != newValue) {
self.willChangeValueForKey("isExecuting")
_executing = newValue
self.didChangeValueForKey("isExecuting")
}
}
}
private var _finished: Bool = false;
override var finished: Bool {
get {
return _finished
}
set {
if (_finished != newValue) {
self.willChangeValueForKey("isFinished")
_finished = newValue
self.didChangeValueForKey("isFinished")
}
}
}
/// Complete the operation
///
/// This will result in the appropriate KVN of isFinished and isExecuting
func completeOperation() {
executing = false
finished = true
}
override func start() {
if (cancelled) {
finished = true
return
}
executing = true
main()
}
}
当我执行这个代码,它口口声声说其运行的主线程上:2016年8月12日18:25:45.799邮票Catalague预加载[1807:31357]主线程?是。
这是怎么发生的?谢谢你的帮助;
你可能已经从[这里]得到了'NSOperation'的子类,但是我已经更新了它(http://stackoverflow.com/questions/27021896/nsurlsession-concurrent-requests-with-alamofire/27022598#27022598)同步执行和完成的getter和setter。请参阅[多核考量](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/NSOperation_class/index.html#//apple_ref/doc/uid/TP40004591-RH2-SW17)讨论哪些会谈关于同步这些的重要性。 – Rob
另外,由于您使用'responseJSON',因此不需要调用'NSJSONSerialization'。这已经为你完成了。 (这就是我们使用'responseJSON'的原因,所以我们不必担心自己解析它。)只需使用'response.result.value'。 – Rob