iOS - 执行在后台写入Core Data的多个AFJSONRequestOperations

时间:2013-01-04 21:06:52

标签: iphone ios core-data afnetworking nsoperationqueue

我无法确定管理应用程序SQLite数据库更新的最佳方法(使用Core Data)

当我的应用程序启动时,它会命中服务器以确定哪些表需要更新。然后,我为每个表执行服务调用。一旦我获得了每个JSON,它就会在我的SQLite DB中创建/更新相应的对象。

我正在做的工作,因为它执行每个请求并更新每个需要的表 - 但我不认为我这样做是正确的。

执行此操作仍会锁定我的UI线程,我需要能够每隔10分钟左右在后台异步运行此代码。

AFJSONRequestOperation* operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {


        NSMutableArray *operations = [NSMutableArray new];

        //for each of the tables that need updating, create a AFJSONRequestOperation
        for(NSString *str in [JSON valueForKey:@"Views"])
        {

            NSString* path = [NSString stringWithFormat:@"cache/%@/?deviceUID=%@&token=%@", str, @"00000-00000-0000-00001", [_globals getToken]];
            NSURLRequest* request = [client requestWithMethod:@"GET" path:path parameters:nil];
            AFJSONRequestOperation* operation2 = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) 
            {
                   [self updateTable:str withJSON:JSON];
            } 
            failure:nil];

            [operations addObject:operation2];
        }

        //AFHTTPClient
        [client enqueueBatchOfHTTPRequestOperations:operations progressBlock:nil completionBlock:^(NSArray *operations) {
            //this gets called way before the objects are done updating to the DB
            NSLog(@"DONE ALL REQUESTS");
            [_HUD hide:YES]; // getting called after getting all of the JSON not after all tables are updated
        }];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

        [_HUD hide:YES];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
    }];


    [operation start];

继承我的updateTable函数只有1个条件

- (void)updateTable:(NSString *)tblName withJSON:(id)JSON
{
    for(NSDictionary *record in [JSON valueForKey:@"Records"])
            {
                NSString *viewName = [[record valueForKey:@"ViewName"] lowercaseString];

                //Worker
                if([viewName isEqualToString:[[NSString stringWithFormat:@"Worker_vw_iSales"] lowercaseString]])
                {
                    if([Worker doesWorkerExist:[record valueForKey:@"JSONData"]])
                    {
                        NSLog(@"deleting old worker");
                        [ad.managedObjectContext deleteObject:[Worker doesWorkerExist:[record valueForKey:@"JSONData"]]];

                    }

                    NSEntityDescription *desc = [NSEntityDescription entityForName:NSStringFromClass([Worker class]) inManagedObjectContext:ad.managedObjectContext];
                    Worker *worker = [[Worker alloc] initWithEntity:desc insertIntoManagedObjectContext:ad.managedObjectContext];
                    [worker initWithJSONSting:[record valueForKey:@"JSONData"]];
                    NSLog(@"Creating Worker: %@", worker.firstName);


                }
    }
}

我希望这不会太令人困惑 - 如果是这样,我可以尝试解释更多。

我可能完全错了,如果我只是让我知道。我尝试了一些其他的东西,包括使用NSOperationQueue而不是AFHHTTP enqueueBatchOfHTTPRequestOperations:requests,但我无法得到我正在寻找的行为。

谢谢!

1 个答案:

答案 0 :(得分:2)

您现在正在寻找AFJSONRequestOperation上的setSuccessCallbackQueue:。除非另有说明,AFNetworking将其所有成功块设置为在主队列上运行。

我所做的是

@implementation myClass {
    dispatch_queue_t backgroundQueue;
}

- (id)init
{
    if (self = [super init]){
        backgroundQueue = dispatch_queue_create("com.proj.myClass", 0);
    }
    return self;
}

- (void)doSomeStuff
{
    NSMutableURLRequest *request = [[myAFAPIClient sharedClient] requestWithMethod:@"GET" path:path parameters:params];
    AFJSONRequestOperation *myOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    //Success Block
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
    }];
[myOperation setSuccessCallbackQueue:backgroundQueue];
[[myAFAPIClient sharedClient].operationQueue addOperation:myOperation];
}

所以不同的是,你们正在进行排队操作,我只是将它们直接添加到客户端。

此外,我有//成功阻止我做了各种各样的事情,比如将其他方法分派到backgroundQueue上,这些方法会产生更多的JSON请求,而且我没有任何问题。