IOS - 文件和文件夹管理
Posted
技术标签:
【中文标题】IOS - 文件和文件夹管理【英文标题】:IOS - file and folder management 【发布时间】:2013-06-10 03:41:36 【问题描述】:我现在正在学习如何在 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 的教程,并在谷歌上搜索了目录创建部分的其他示例。好像出了什么问题??谢谢!
【问题讨论】:
【参考方案1】:问题出在这一行:
if ([filemgr fileExistsAtPath:@"newfolder" isDirectory:&isDir] && isDir)
NSLog(@"folder already created!");
您需要将完整路径作为
fileExistsAtPath
的参数传递给Like:
NSSTring *folderPath = [docsDir stringByAppendingPathComponent:
@"newfolder"];
if ([filemgr fileExistsAtPath:folderPath isDirectory:&isDir] && isDir)
NSLog(@"folder already created!");
【讨论】:
【参考方案2】:这里是更新的工作版本,以防有人在寻找它:
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];
【讨论】:
这应该是您问题的一部分,而不是额外的答案。它所做的只是插入另一个答案中包含的信息。以上是关于IOS - 文件和文件夹管理的主要内容,如果未能解决你的问题,请参考以下文章
iOS学习之文件管理器(NSFileManager)和文件对接器(NSFileHandle)