アプリの 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];
条件が 1 つだけの私の updateTable 関数を次に示します。
- (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);
}
}
}
これがあまり混乱しないことを願っています-もしそうなら、もっと説明しようとすることができます.
私はこれを完全に間違っているかもしれません。AFHHTTPs の代わりに NSOperationQueue を使用するなど、他にもいくつか試しましたenqueueBatchOfHTTPRequestOperations:requests
が、探している動作が得られません。
ありがとう!