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

时间:2015-07-29 05:27:56

标签: 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];
  }

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

1 个答案:

答案 0 :(得分:2)

使用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
}];