简体   繁体   English

文档目录中的读/写文件问题

[英]Read/write file in Documents directory problem

I am trying to write a very basic text string to my documents directory and work from there to later save other files etc. 我正在尝试将一个非常基本的文本字符串写入我的文档目录,并从那里开始工作,以后保存其他文件等。

I am currently stuck with it not writing anything into my Documents directory 我目前坚持不在我的Documents目录中写任何东西

(In my viewDidLoad ) (在我的viewDidLoad

NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
NSString *documentsDirectory = [pathArray objectAtIndex:0];

NSString *textPath = [documentsDirectory stringByAppendingPathComponent:@"file1.txt"];
NSString *text = @"My cool text message";

[[NSFileManager defaultManager] createFileAtPath:textPath contents:nil attributes:nil];
[text writeToFile:textPath atomically:NO encoding:NSUTF8StringEncoding error:NULL];
NSLog(@"Text file data: %@",[[NSFileManager defaultManager] contentsAtPath:textPath]);

This is what gets printed out: 这是打印出来的:

2011-06-27 19:04:43.485 MyApp[5731:707] Text file data: (null) 2011-06-27 19:04:43.485 MyApp [5731:707]文本文件数据:(null)

If I try this, it also prints out null: 如果我试试这个,它也打印出null:

NSLog(@"My Documents: %@", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:NULL]);

What have I missed or am I doing wrong while writing to this file? 在写这个文件的时候我错过了什么或者我做错了什么? Might it be something I need to change in my plist or some frameworks/imports needed? 可能是我需要在我的plist或某些框架/导入需要更改的东西吗?

Thanks 谢谢

[EDIT] I passed a NSError object through the writeToFile and got this error: [编辑]我通过writeToFile传递了一个NSError对象并得到了这个错误:

Error: Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn't be completed. (Cocoa error 512.)" UserInfo=0x12aa00 {NSFilePath=/var/mobile/Applications/887F4691-3B75-448F-9384-31EBF4E3B63E/Documents/file1.txt, NSUnderlyingError=0x14f6b0 "The operation couldn't be completed. Not a directory"} 错误:错误Domain = NSCocoaErrorDomain Code = 512“操作无法完成。(Cocoa错误512.)”UserInfo = 0x12aa00 {NSFilePath = / var / mobile / Applications / 887F4691-3B75-448F-9384-31EBF4E3B63E / Documents / file1.txt,NSUnderlyingError = 0x14f6b0“操作无法完成。不是目录”}

[EDIT 2] This works fine on the simulator but not on my phone :/ [编辑2]这在模拟器上工作正常,但在我的手机上没有:/

Instead of using NSFileManager to get the contents of that file, try using NSString as such: 而不是使用NSFileManager来获取该文件的内容,请尝试使用NSString:

NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
NSString *documentsDirectory = [pathArray objectAtIndex:0];
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:@"file1.txt"];
NSError *error = nil;
NSString *str = [NSString stringWithContentsOfFile:textPath encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
    NSLog(@"There was an error: %@", [error description]);
} else {
    NSLog(@"Text file data: %@", str);
}

Edit: Added error checking code. 编辑:添加了错误检查代码。

How are you getting documentsDirectory ? 你怎么得到documentsDirectory

You should be using something like this: 你应该使用这样的东西:

NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)

NSString *documentsDirectory = [pathArray lastObject];

You can also use NSFileHandle for writing data in file and save to document directory: 您还可以使用NSFileHandle在文件中写入数据并保存到文档目录:

Create a variable of NSFileHandle 创建NSFileHandle的变量

NSFileHandle *outputFileHandle;

use the prepareDataWrittenHandle function with passing file name in parameter with file extension 使用prepareDataWrittenHandle函数,在带有文件扩展名的参数中传递文件名

-(void)prepareDataWrittenHandle:(NSString *)filename
{
    //Create Path of file in document directory.
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *outputFilePath = [documentsDirectory stringByAppendingPathComponent:filename];

    //Check file with above name is already exits or  not.
    if ([[NSFileManager defaultManager] fileExistsAtPath:outputFilePath] == NO) {
        NSLog(@"Create the new file at outputFilePath: %@", outputFilePath);

        //Create file at path.
        BOOL suc = [[NSFileManager defaultManager] createFileAtPath:outputFilePath
                                                           contents:nil
                                                         attributes:nil];
        NSLog(@"Create file successful?: %u", suc);
    }

    outputFileHandle = [NSFileHandle fileHandleForWritingAtPath:outputFilePath];
}

then write the string value to file as: 然后将字符串值写入文件:

//Create a file
[self prepareDataWrittenHandle:@"file1.txt"];

//String to save in file
NSString *text = @"My cool text message";

//Convert NSString to NSData to save data in file.
NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding]

//Write NSData to file
[_outputFileHandle writeData:data];

//close the file if written complete
[_outputFileHandle closeFile];

at the end of file written you should close the file. 在文件结尾处,您应该关闭该文件。

You can also check the content written in file as NSString for debug point of view as mention above by @Glenn Smith: 如上所述,@ Glenn Smith还可以检查文件中写入的内容为NSString以获得调试的观点:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *outputFilePath = [documentsDirectory stringByAppendingPathComponent:@"file1.txt"];

NSError *error;
NSString *str = [NSString stringWithContentsOfFile:outputFilePath encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
    NSLog(@"There was an error: %@", [error description]);
} else {
    NSLog(@"Text file data: %@", str);
}

Put an NSLog statement after every line where you are setting a variable's value, so that you can inspect those values. 在设置变量值的每一行之后放置一条NSLog语句,以便检查这些值。 This should help you quickly pinpoint where things start to go wrong. 这应该可以帮助您快速查明出现问题的地方。

The problem got solved by setting a non standard Bundle ID in die info.plist 通过在info.plist中设置非标准Bundle ID解决了这个问题

I used the Bundle ID from iTunes Connect for this specific app. 我使用iTunes Connect中的Bundle ID来获取此特定应用。 Now everything works perfectly. 现在一切都很完美。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM