我正在学习如何在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中的教程进行操作,并在其他示例中查看目录创建部分。什么似乎出错?谢谢!
答案 0 :(得分:2)
问题出在这一行:
if ([filemgr fileExistsAtPath:@"newfolder" isDirectory:&isDir] && isDir) {
NSLog(@"folder already created!");
您需要将完整路径作为
fileExistsAtPath
的参数传递,如:
NSSTring *folderPath = [docsDir stringByAppendingPathComponent:
@"newfolder"];
if ([filemgr fileExistsAtPath:folderPath isDirectory:&isDir] && isDir) {
NSLog(@"folder already created!");
答案 1 :(得分:0)
以下是更新的工作版本,以防有人在寻找它:
newDir = [docsDir stringByAppendingPathComponent:@"newfolder"];
if ([filemgr fileExistsAtPath:newDir isDirectory:&isDir] && isDir) {
NSLog(@"folder already created!");
}else{
NSLog(@"create new folder now...");
[filemgr createDirectoryAtPath:newDir withIntermediateDirectories:YES
attributes:nil error: NULL];
}