gpt4 book ai didi

IOS——文件和文件夹管理

转载 作者:行者123 更新时间:2023-11-28 22:32:27 24 4
gpt4 key购买 nike

我现在正在学习如何在 iOS 中创建和管理文件和文件夹。但我似乎无法正确处理文件夹部分。我下面的代码有什么问题?

- (void)viewDidLoad
{
[super viewDidLoad];
NSFileManager *filemgr;
NSString *dataFile;
NSString *docsDir;
NSString *newDir;
NSArray *dirPaths;
BOOL isDir;

filemgr = [NSFileManager defaultManager];

// Identify the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);

docsDir = dirPaths[0];

// Build the path to the data file
if ([filemgr fileExistsAtPath:@"newfolder" isDirectory:&isDir] && isDir) {
NSLog(@"folder already created!");
}else{
NSLog(@"create new folder now...");
newDir = [docsDir stringByAppendingPathComponent:@"newfolder"];
}

dataFile = [docsDir stringByAppendingPathComponent:
@"/newfolder/datafile.dat"];

// Check if the file already exists
if ([filemgr fileExistsAtPath: dataFile])
{
// Read file contents and display in textBox
NSData *databuffer;
databuffer = [filemgr contentsAtPath: dataFile];

NSString *datastring = [[NSString alloc]
initWithData: databuffer
encoding:NSASCIIStringEncoding];

_textBox.text = datastring;
}

}


- (IBAction)saveText:(id)sender {
NSFileManager *filemgr;
NSData *databuffer;
NSString *dataFile;
NSString *docsDir;
NSArray *dirPaths;

filemgr = [NSFileManager defaultManager];

dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);

docsDir = dirPaths[0];
dataFile = [docsDir
stringByAppendingPathComponent: @"/newfolder/datafile.dat"];
databuffer = [_textBox.text
dataUsingEncoding: NSASCIIStringEncoding];
[filemgr createFileAtPath: dataFile
contents: databuffer attributes:nil];
}

我不确定会发生什么,但每次我运行模拟时,它都会给我一个空白文本字段,尽管我之前已经输入了一些文本。我遵循了 Here 中的教程并用谷歌搜索目录创建部分的其他示例。好像出了什么问题??谢谢!

最佳答案

问题出在这一行:

if ([filemgr fileExistsAtPath:@"newfolder" isDirectory:&isDir] && isDir) {
NSLog(@"folder already created!");

You need to pass the complete path as argument of fileExistsAtPath Like:

NSSTring *folderPath = [docsDir stringByAppendingPathComponent:
@"newfolder"];
if ([filemgr fileExistsAtPath:folderPath isDirectory:&isDir] && isDir) {
NSLog(@"folder already created!");

关于IOS——文件和文件夹管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17016601/

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