ios - 加快将大量 JSON 数据写入磁盘的速度

标签 ios objective-c json core-data file-io

我有一个大概有 40k 条记录的循环,基本上可以调用。似乎写入文件真的很慢。如果我遍历循环,它几乎是即时的,所以我意识到它不是核心数据迭代,而是文件写入过程。有没有比我在这里做的更好的方法将数据流式传输到文件?

#ifndef jsonAppend
#define jsonAppend(X) [outStream write:[[X dataUsingEncoding:NSUTF8StringEncoding ] bytes] maxLength:[X lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]
#endif



NSOutputStream *outStream = [NSOutputStream outputStreamToFileAtPath:tempFilePath append:NO];

    dispatch_async(backgroundQueue, ^{

// Open an output stream to write to.
[outStream open];

// Other code ... blablabla

for (AHRSMessage *msg in results)
{

    @autoreleasepool
    {

        [NSJSONSerialization writeJSONObject:msg.attributesAsDictionary toStream:outStream options:0 error:&error];
        jsonAppend(@",\n");

        i++;  // MessageCounter


        // Update UI only sometimes
        if (i % 100)
        {

            dispatch_async(dispatch_get_main_queue(), ^
            {
                @autoreleasepool {


                    float pct = i / recordCount ;
                    NSString *pctStr = [NSString stringWithFormat:@"%02.0f%%", pct * 100.0];
                    [[weakSelf percentLabel] setText:pctStr];
                    [[weakSelf parsingProgress] setProgress:pct animated:YES];

                    /* - Animate inner circle on units of 1% - */
                    int singPctMsgCount = recordCount / 100;
                    float fastParse = (i % singPctMsgCount) / (float)singPctMsgCount;
                    [[weakSelf fastParsingProgress] setProgress:fastParse animated:YES]     ;

                    [weakSelf updateUI];

                }
            });

        }

    }
} // end for loop

});

最佳答案

因为它只有 18MB,只需将它序列化为一个 NSMutableData 对象,然后将其写入磁盘。

那应该非常快。 NSMutableData 可以轻松处理甚至无法放入闪存(假设您有 64 位处理器)的数据量,更不用说 iOS 设备上的 RAM 了。

像这样:

dispatch_async(backgroundQueue, ^{

  NSMutableData *outData = [NSMutableData data];

  // Other code ... blablabla

  for (AHRSMessage *msg in results)
  {

      @autoreleasepool
      {
          [outData appendData:[NSJSONSerialization dataWithJSONObject:msg.attributesAsDictionary options:0 error:&error];

          i++;  // MessageCounter


          // Update UI only sometimes
          if (i % 100)
          {

              dispatch_async(dispatch_get_main_queue(), ^
              {
                  @autoreleasepool {

                      ... update progress bar ...

                  }
              });

          }

      }
  } // end for loop

  [outData writeToURL:outURL atomically:YES];
});

此外,我不会使用 if (i % 100) 来决定是时候更新进度条了。相反,我会使用:

CFTimeInterval lastProgressUpdate = CACurrentMediaTime();

for (  ... ) {
  ...

  if (CACurrentMediaTime() - lastProgressUpdate > 0.02) { // 1/60th of a second. Which is the refresh rate of most LCD screens
    ... update progress bar ....

    lastProgressUpdate = CACurrentMediaTime()
  }
}

关于ios - 加快将大量 JSON 数据写入磁盘的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23088633/

相关文章:

Objective-C 原始数组

java - 使用 JSweet 将 map 发布为 JSON

json - MongoDB : Update Modifier semantics of "$unset"

json - 如何使用jq解析json对象而不是数组

android - 如何从 iOS 和 Android 上的 PhoneGap 搜索 native Google map 应用程序中的文本字符串?

ios - 动画按钮 360 顺时针旋转和反向旋转

c++ - 为 iOS 编译 OpenFST 时出现转换错误

ios - 混淆xcode?带有建议格式修复的警告,然后下一次编译要将其切换回来吗?

ios - 多次获取第一个视频轨道,同时尝试使用 AVFoundation 将三个不同的视频轨道组合在同一帧中

objective-c - 多点触控基础知识(3 个或更多手指)