ios - 如何在 ios 中异步读取 Documents 目录中的文件

标签 ios objective-c asynchronous file-read

我想异步读取存储在 Documents 目录中的本地文件。我的代码如下:

-(NSString *)getLogFilePath
{
    NSString *logFileNameString = logFile;
    return  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:logFileNameString];
}


 -(NSString *)readStringFromFile
  {
  NSString *fileAtPath =  [self getLogFilePath];
  return [[NSString alloc] initWithData:[NSDataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
  }

有人请在这方面帮助我。 提前致谢。

最佳答案

使用 Grand Central Dispatch 和 Block 语法来做到这一点,

+(void) readStringFromFileWithCompletion:(void (^)(BOOL success,NSString *output))completionBlock{


dispatch_queue_t myQueue = dispatch_queue_create("FileReadingQueue",NULL);
dispatch_async(myQueue, ^{
    // Perform long running process
    NSString *fileAtPath =  [self getLogFilePath];
    NSString *output = [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];

    completionBlock(true,output);

});

用你的方法,

[self readStringFromFileWithCompletion:^(BOOL success, NSString *output) {
    // use 'output' here, to get the string read from file
}];

关于ios - 如何在 ios 中异步读取 Documents 目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31691845/

相关文章:

iphone - 核心数据故障 : how to load an entities relationship set of objects correctly

ios - UINavigation : Rules on how to present Viewcontroller (push/replace)

iphone - 是否有来自 Java 的 currentTimeMillis() 的 objective-c/iPhone 版本?

ios - 为什么在使用 ARC block 时出现 EXC_BAD_ACCESS_EXCEPTION(代码= EXC_ARM_DA_ALIGN)?

c++ - 重叠/异步 I/O 如何工作

C#/WPF 使用异步和等待,但 UI 线程仍然被阻塞

iOS 应用内购买 : request latest cancellation date and number of cancellations

ios - 设备方向改变问题

ios - 使用 2 个 UIButton 模拟 UISegmentedControl

html - 如何在 HTML 应用程序中异步运行脚本?