Reputation: 2035
I'm trying to append some text to a file that resides in the application bundle with the following code:
NSString *dotsStr = [NSString stringWithFormat:@"%i", dots];
NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%i_500", dots] ofType:@"txt"];
NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSASCIIStringEncoding error:nil];
NSString *newpath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%i_50", dots] ofType:@"txt"];
[contents appendToFile:newpath encoding:NSASCIIStringEncoding];
When appending to the file, I'm using a category on NSString:
- (BOOL) appendToFile:(NSString *)path encoding:(NSStringEncoding)enc;
{
BOOL result = YES;
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:path];
if (!fh)
{
[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
fh = [NSFileHandle fileHandleForWritingAtPath:path];
}
if (!fh) return NO;
@try {
[fh seekToEndOfFile];
[fh writeData:[self dataUsingEncoding:enc]];
}
@catch (NSException * e)
{
result = NO;
}
[fh closeFile];
return result;
}
This is working fine on the simulator, however, when I restart the app, the old file gets loaded, without the appended text. I have no idea how this is possible.
Does anyone know how I could change this category so that the changes are persistent?
Thanks in advance! :)
Upvotes: 0
Views: 555
Reputation:
You can't write to the app bundle.
(For quite obvious security reasons, by the way.)
If you're intending to change a file, copy it to a writable location, for example in the Documents directory.
(Oh, and before you ask it: the simulator uses OS X's file system, where this restriction is not present, so that's why it works on the simulator. Another thing the simulator fails to simulate.)
Upvotes: 4
Reputation: 1359
Application bundle is read-only. You need to copy your file to application's Documents directory before modifying it.
Upvotes: 2