Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
789 views
in Technique[技术] by (71.8m points)

iphone - 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

(In my 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)

If I try this, it also prints out 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?

Thanks

[EDIT] I passed a NSError object through the writeToFile and got this error:

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"}

[EDIT 2] This works fine on the simulator but not on my phone :/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of using NSFileManager to get the contents of that file, try using NSString as such:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...