NSOperation
的子类,用于管理一个块的并发执行。
您可以直接使用 MROperation
对象
MROperation *someOperation = [[MROperation alloc] initWithBlock:^(id<MRExecutingOperation> *operation) {
// long ruinning task...
if (operation.isCancelled) return;
// long ruinning task...
if (!operation.isFinished) [operation finishWithError:nil];
};
[someOperation start];
但您也可以实现自己的子类。以下是如何创建用于执行反向地理编码请求的自定义子类的示例
// MROperation subclass that performs reverse-geocoding requests.
@interface GeocodingRequestOperation : MROperation
// Returns a reverse-geocoding request operation for the given location.
+ (instancetype)operationWithLocation:(CLLocation *)location;
// The result of the reverse-geocoding request.
@property (nonatomic, strong) CLPlacemark *placemark;
@end
@implementation GeocodingRequestOperation
+ (instancetype)operationWithLocation:(CLLocation *)location {
return [[self alloc] initWithBlock:^(GeocodingRequestOperation<MRExecutingOperation> *operation) {
[[[CLGeocoder alloc] init] reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
operation.placemark = placemarks.firstObject;
if (!operation.isFinished) [operation finishWithError:error];
}];
}];
}
@end
以下是执行它们的示例
// Set up a queue:
_geocodingQueue = [[NSOperationQueue alloc] init];
_geocodingQueue.maxConcurrentOperationCount = 1;
// Create and configure the reverse-geocoding request operation:
GeocodingRequestOperation *o = [GeocodingRequestOperation operationWithLocation:location];
[o setCompletionBlockWithSuccess:^(GeocodingRequestOperation *operation) {
NSLog(@"Hello %@!", operation.placemark.country);
} failure:^{
NSLog(@"%@", error);
}];
// Add the operation to the queue:
[_geocodingQueue addOperation:o];
有关如何子类化 MRoperation
的另一个示例,您可以参考 MRDetectBpmOperation
的 实现。
将 MROperation 文件夹拖到您的项目中。
MROperation 可在 MIT 许可证下使用。有关更多信息,请参阅 LICENSE 文件。