Search code examples
objective-cnsarraywritetofile

objective-c simple nsarray writeToFile issue


[wordlist writeToFile:[[NSBundle mainBundle] 
pathForResource:@"wordlist" ofType:@"txt"] atomically: YES];

wordlist is a NSMutableArray, and the rest you know what.

The problem is that nothing is saved in wordlist.txt when I run the codes in Xcode. In front of this code nslog shows that there are 4 objects in wordlist. How come?


Edit: Right!

These codes work!:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *yourArrayFileName = [documentsDirectory stringByAppendingPathComponent:@"wordlist.txt"];  
[wordlist writeToFile:yourArrayFileName atomically:YES];    
NSLog (@"%@", yourArrayFileName);

Edit 29 august 2011.

NSString *documentsDirectory = @"/Users/YOURNAME/Desktop/";
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"norsk.txt"];

    NSString *content = @"æ ø å";
    BOOL ok = [content writeToFile:appFile atomically:YES encoding:NSUnicodeStringEncoding error:nil];
    if (!ok) {
        NSLog(@"Error writing file !");
    }

also works!


Solution

  • You can't write in you app's bundle.

    You need to write in the user's directory. You can know more about it in this question.

    There's three directory you can write in

    • NSDocumentDirectory : the document directory. The user will be able to see these file. This should be for user files only. Backed up by iTunes.
    • NSCachesDirectory : the cache directory is where you place things you app may need in the future, but that you can reconstruct. Not backed up by iTunes.
    • NSApplicationSupportDirectory : the application support is where you place your essential files for your application. Backed up by iTunes.