iOS : I can't write my file

2020-05-07 04:32发布

问题:

I want to write a file on my iPhone app. My file is in my project's folder, but when I try to reach it :

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

I get the following path :

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

Why ?

Thanks for your advices

回答1:

You ask:

Why?

It's that path because that's where the file is stored.

On the device it will be different.

Note that you can't write a file to that folder anyway. You should perhaps instead write to your app's documents folder:

//Get the documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];

//Get the final path of your file.
NSString *finalPath = @"myfile.txt"];    
//And actually write that file.
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:/*fileData as NSData*/ attributes:nil];


回答2:

As already said you can't write to the main bundle on an actual device.

To your other question:

When you run your app in the simulator xcode will copy your project to a folder in your library directory .. in your case to:

/Users/Damian/Library/Application Support/iPhone Simulator/5.1/Applications/

Every app you run in your simulator has a folder there. Apps are not run in the folders where you actually edit your code.