RESTKit 0.20操作队列

时间:2014-04-18 06:23:18

标签: restkit-0.20

我正在尝试实现RESTKit 0.20操作队列,我在博客上读到NSOperationQueue也可用于创建操作队列。我想使用RestKit操作队列的本机方法。

任何人都可以发布以下代码/示例:

  • 如何在RestKit中使用操作队列。
  • 设置队列以一次执行一个操作。
  • 如果第一个操作没有完成,那么我需要取消此队列中的待处理操作。

期待听到你的意见。

感谢。

1 个答案:

答案 0 :(得分:6)

在这里,我将与您分享我用于ManagedObjects(CoreData Objects)请求操作的代码。

获取对objectManager&amp ;;的引用managedObjectContext;

RKObjectManager *objectManager = [(AppDelegate *)[[UIApplication sharedApplication] delegate] objectManager];
NSManagedObjectContext *managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

初始化数组以阻止其中的操作

NSMutableArray *requestOperations = [NSMutableArray array];

准备第一个操作并将其添加到requestOperations数组,注意故障块正在取消队列中的待处理操作。

// Setup Organization Operation
//
NSString *url = @"organizations/syncAll/";
NSMutableURLRequest *organizationsRequest = [objectManager requestWithObject:organizations method:RKRequestMethodPOST path:url parameters:nil];

RKObjectRequestOperation *organizationsOperation = [objectManager managedObjectRequestOperationWithRequest:organizationsRequest managedObjectContext:managedObjectContext success: ^(RKObjectRequestOperation *operation, RKMappingResult *result) {

    ..

    [RKUtils isHandleStatusError:[result array]];
} failure: ^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"Failed with error: %@", [error localizedDescription]);

    [objectManager cancelAllObjectRequestOperationsWithMethod:RKRequestMethodPOST matchingPathPattern:@"games/getNotStartedGames"];
    [RKUtils handleError:error];
}];
[requestOperations addObject:organizationsOperation];

准备第二次操作

// Setup Games Operation
//
url = @"games/syncAll/";
NSMutableURLRequest *gamesRequest = [objectManager requestWithObject:games method:RKRequestMethodPOST path:url parameters:nil];

RKObjectRequestOperation *gamesOperation = [objectManager managedObjectRequestOperationWithRequest:gamesRequest managedObjectContext:managedObjectContext success: ^(RKObjectRequestOperation *operation, RKMappingResult *result) {

    ..

    [RKUtils isHandleStatusError:[result array]];
} failure: ^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"Failed with error: %@", [error localizedDescription]);

    if (error.code == NSURLErrorCancelled) {
        return;
    }

    [RKUtils handleError:error];
}];
[requestOperations addObject:gamesOperation];

准备更多操作

..

将最大并发操作数设置为1

objectManager.operationQueue.maxConcurrentOperationCount = 1;

将所有操作排入队列。队列将逐个开始执行操作。

// Enqueue Request Operations
[objectManager enqueueBatchOfObjectRequestOperations:requestOperations progress: ^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
    NSLog(@"totalNumberOfOperations : %d", totalNumberOfOperations);
    NSLog(@"numberOfFinishedOperations : %d", numberOfFinishedOperations);
} completion: ^(NSArray *operations) {
    NSLog(@"completion");
}];

希望能实现你的目的。 欢呼声,