iOS - 客户端网络请求 - 数据处理
已知:iOS客户端,在某个界面,连网时,需向后台请求数据,断网时,读取本地数据
问题:数据量大时,如何处理这么庞大的数据?
解决方法:先读取本地数据,再从线上请求数据,与本地数据比较,更新本地数据,再次从读取本地数据。
[self loadFromDb]; if (![[Helper isExistenceNetwork] isEqualToString:@"NotReachable"]) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self loadFromService]; }); }
#pragma mark - 读取数据库 - (void)loadFromDb { FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; if (![db open]) { NSLog(@"Could not open db."); return; } FMResultSet *blogListResult; blogListResult = [db executeQueryWithFormat:@"select语句]; blogsData = [[NSMutableDictionary alloc] init]; oldListSource = [[NSMutableArray alloc] init]; while ([blogListResult next]) { NSMutableDictionary *blogsDic = [[NSMutableDictionary alloc] init]; // 组装数据 [blogsDic setObject:STATUS_DELETE forKey:@"status"]; NSString *key =[NSString stringWithFormat:@"%@", [blogsDic objectForKey:@"id"]]; [blogsData setObject:blogsDic forKey:key]; [blogsListSource addObject:blogsDic]; [oldListSource addObject:blogsDic]; } [db close]; [self reloadSource]; }
- (void)requestFinished:(ASIHTTPRequest *)request { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSDictionary *result = [[[NSString alloc] initWithData:[request responseData] encoding:NSUTF8StringEncoding] objectFromJSONString]; NSArray *blogListAry = [result objectForKey:@"blogList"]; BOOL isChanged = NO; FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; if (![db open]) { NSLog(@"Could not open db."); return; } if ([blogListAry count] != [oldListSource count]) { isChanged = YES; } for (int i = 0; i < [blogListAry count]; i++) { NSDictionary *blogs = [blogListAry objectAtIndex:i]; if ([blogsData objectForKey:[NSString stringWithFormat:@"%@", [blogs objectForKey:@"id"]]]) { NSMutableDictionary *oldSpace = [blogsData objectForKey:[NSString stringWithFormat:@"%@", [blogs objectForKey:@"id"]]]; //更新本地数据库 isChanged = YES;
//改变oldSpace中key的值也就相当于改变了oldListSource中key的值 [oldSpace setObject:STATUS_NORMAL forKey:@"status"]; }else{ //插入本地数据库 isChanged = YES; } } if (isChanged) { for (int i = 0; i < [oldListSource count]; i++) { NSMutableDictionary *oSpace = [oldListSource objectAtIndex:i]; if ([[oSpace objectForKey:@"status"] isEqualToString:STATUS_DELETE]) {
//删除数据库多余的数据 } } dispatch_async(dispatch_get_main_queue(), ^{ [self loadFromDb]; }); } }); }
OK,第一篇博客写完了。