Reputation: 1462
I'm beginning to store an NSArray in file, but I keep getting nil as a response...
The Apple docs say that nil means your file doesn't exist, but I'm pretty sure mine does (I'm probably not building my path correctly)...
Here is the code that I use to store my NSArray in a file...
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"scorecards" ofType:@"dgs"];
NSArray *myArray = [[NSArray alloc] initWithObjects:@"J", @"ANA", @"MY", @"GDON", nil];
[myArray writeToFile:filePath atomically:YES];
NSArray *mynewArray = [NSArray arrayWithContentsOfFile:filePath];
NSLog(@"%@", [mynewArray objectAtIndex:2]);
I also took a screenshot of Xcode to show you guys that my file does exist...
The file is clearly saved in the group ScorecardsSaved and the file is called scorecards with the extension dgs (something I made up for my specific application - Dot Golf Scorecard - dgs)
Upvotes: 0
Views: 145
Reputation: 1271
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];
[myArray writeToFile:filePath atomically:YES];
Upvotes: 1
Reputation: 80265
Indeed, your file path uses the pathForResource
method, thus it will point to a location in your application bundle, which is not writable.
Instead, you have to write to the application document directory on the device / simulator.
NSURL *documentsDirectory =
[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
NSURL *fileURL = [documentsDirectory
URLByAppendingPathComponent:@"storecards.dgs"];
So if your bundle version of the document contains some seed data, copy it to the app documents directory first.
Upvotes: 2