gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:46:50 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com