ManagedOperation
是 NSOperation
的实现,用于抽象和处理异步任务。
Cocoapods
pod "ManagedOperation"
在Objective-C中的导入
#import <ManagedOperation/ManagedOperation-Swift.h>
在Swift中的导入
import ManagedOperation
假设您有一个耗时的任务,您希望在一个后台线程上执行。
ManagedOperation为您提供了两种在异步NSOperation
中包装任务的选择
ManagedBlockOperation
let asyncOperation = ManagedBlockOperation() { operation in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// perform time-consuming task
operation.completed = true
}
}
ManagedOperation
class SampleAsyncOperation : ManagedOperation {
override func start() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { [weak self] in
// perform time-consuming task
self!.completed = true
}
}
此外,还有一个扩展了‘NSOperationQueue’,可以轻松创建
操作按列表顺序一个接一个执行
let operations = [SampleAsyncOperation(),SampleAsyncOperation()];
let _ = NSOperationQueue.createSequentalQueue(operations) { () -> () in
//called when all NSOperations are completed.
}
操作以并发方式执行
let operations = [SampleAsyncOperation(),SampleAsyncOperation()];
let _ = NSOperationQueue.createConcurrentQueue(operations) { () -> () in
//called when all NSOperations are completed.
}
请参见 ManagedOperationTests.swift
的示例用法。
ManagedOperation是在MIT许可证下发布的。