我无法确定管理我的应用程序 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 而不是 AFHHTTPs,enqueueBatchOfHTTPRequestOperations:requests
但我无法获得我正在寻找的行为。
谢谢!