File write with [NSBundle mainBundle] fails

In iOS, you can't write into a file in your app's bundle -- the entire bundle is read-only. Use a path into the Documents folder instead.


See special File System Programming Guide for better understnading.
In iOS, you can't write into a file in your app's bundle -- the entire bundle is read-only.

Consider reading iOS Data Storage Guidelines to better understand the purpose of directories below, in context of iCloud backup.

<Application_Home>/AppName.app

This is the bundle directory containing the app itself. Do not write anything to this directory. To prevent tampering, the bundle directory is signed at installation time. Writing to this directory changes the signature and prevents your app from launching again.


<Application_Home>/Documents/

Use this directory to store critical user documents and app data files. Critical data is any data that cannot be recreated by your app, such as user-generated content. The contents of this directory can be made available to the user through file sharing. The contents of this directory are backed up by iTunes.


<Application_Home>/Library/

This directory is the top-level directory for files that are not user data files. You typically put files in one of several standard subdirectories but you can also create custom subdirectories for files you want backed up but not exposed to the user. You should not use this directory for user data files. The contents of this directory (with the exception of the Caches subdirectory) are backed up by iTunes. For additional information about the Library directory, see “The Library Directory Stores App-Specific Files.”

See full list (tmp/, Documents/Inbox) in iOS Standard Directories: Where Files Reside

UPDATE
I use NSFileManager method URLForDirectory:inDomain:appropriateForURL:create:error:


Like Caleb said, you can't write to your app's directory, but you can write to your app's Documents folder. You can get it like this:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

Your app's bundle is read-only. There is two ways I could see:

1) Write in documents folder:

NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path =  [myPathList  objectAtIndex:0];

2) Use sqlite database. This is the same as 1 (you must save db in documents anyway), but you're using sqlite database. I think this is better than a lot of txt and plist files: here's a tutorial on the topic.