我想异步读取存储在 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/