(iOS)脱机同步数据库 – 服务器

前端之家收集整理的这篇文章主要介绍了(iOS)脱机同步数据库 – 服务器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试实现一个应用程序,该应用程序在连接到Internet时将存储在本地数据库中的脱机数据发送到Web服务器我使用下面显示代码.到目前为止,我测试它工作正常,不确定它将适用于大量的记录.我想知道是否对此代码进行任何调整可能会提高性能???

注意

>我知道这将是用于离线同步目的的最差代码,所以尝试
更好地调整它.
>从应用程序到服务器的单向同步.

  1. -(void)FormatanswersInJSON {
  2.  
  3. DMInternetReachability *checkInternet = [[DMInternetReachability alloc] init];
  4. if ([checkInternet isInternetReachable]) {
  5. if ([checkInternet isHostReachable:@"www.apple.com"]) {//Change to domain
  6. responseArray = [[NSMutableArray alloc] init];
  7.  
  8. dispatch_async(backgroundQueue,^(void) {
  9.  
  10. NSArray *auditIDArray = [[NSArray alloc] initWithArray: [self getUnuploadedIDs]];
  11. for (int temp = 0; temp < [auditIDArray count]; temp ++) {
  12.  
  13. // Code to post JSON to server
  14.  
  15. NSURLResponse *response;
  16. NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  17. if (!error) {
  18. NSString *responseID = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
  19. if ([responseID isEqualToString:@"ERROR"]) {
  20. //Error uploading records
  21. } else {
  22. [responseArray addObject:responseID];
  23. }
  24. } else {
  25. //Error
  26. return;
  27. }
  28. }
  29. dispatch_async( backgroundQueue,^{
  30.  
  31. /* Based on return code update local DB */
  32. for (int temp = 0; temp < [responseArray count]; temp ++) {
  33. [self updateRecordsForID:[auditIDArray objectAtIndex:temp] withID:[responseArray objectAtIndex:temp]];
  34. }
  35. });
  36. });
  37. }
  38. }
  39. }
  40.  
  41. - (void)upload { //Called when internet connection available
  42.  
  43. if(backgroundQueue){
  44. dispatch_suspend(backgroundQueue);
  45. dispatch_release(backgroundQueue);
  46. backgroundQueue = nil;
  47. }
  48. backgroundQueue = dispatch_queue_create("com.XXXX.TestApp.bgqueue",NULL);
  49. dispatch_async(backgroundQueue,^(void) {
  50. [self FormatanswersInJSON];
  51. });
  52. }

解决方法

如果这个代码放在我面前,我的方法是:

>查看用例并定义“大量记录”:是否会定期更新50条记录?或者是1s和2s?我的用户是否有wifi连接或是通过付费网络?等
>如果可能的话,在野外进行测试.如果我的用户群足够小,请收集实际数据并指导我的决策,或者仅将功能发布到用户/ beta测试和测量的子集.
>如果数据告诉您,则优化此代码以提高效率.

我的优化途径是进行组处理.粗略的算法将是这样的:

  1. for records in groups of X
  2. collect
  3. post to server {
  4. on return:
  5. gather records that updated successfully
  6. update locally
  7. }

这假设您可以修改服务器代码.你可以做10,20,50等组,所有这些都取决于发送的数据类型和大小.

组算法意味着更多的预处理客户端,但具有减少HTTP请求的优点.如果您只是获得少量更新,那么这是YAGNI和预成熟优化.

不要让这个决定阻止你运输!

猜你在找的iOS相关文章