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
589 views
in Technique[技术] by (71.8m points)

objective c - How to read/write file with iOS, in simulator as well as on device?

As I need to read a file when my app is launched and write it sometimes while using it, I tried to reach it with :

NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];
NSLog(@"%@",dataFile);

And the file, that should be in my project folder, is instead in the simulator folder :

2012-06-13 17:36:56.398 MyFileApp[610:15203] /Users/Rob/Library/Application Support/iPhone Simulator/5.1/Applications/1FFD4436-DCCA-4280-9E47-F6474BEE0183/MyFileApp.app/myFile.txt

So if I want to read/write it in using the simulator as well as the real device, what should I do ?

Thanks for your advices

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

To read the file from the bundle do the following

NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];

To read it from your sandbox storage (documents)

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/YourFile.txt"];
NSString *dataFile = [NSString stringWithContentsOfFile:docPath 
                                           usedEncoding:NSUTF8StringEncoding 
                                                  error:NULL];

To write to document folder

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/YourFile.txt"];
[dataFile writeToFile:docPath 
          atomically:YES 
            encoding:NSUTF8StringEncoding 
               error:NULL];

Please note you will not be able to write the file in the bundle folder of your application


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

...