(void) loadDataFromDisk
{
NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:[self pathToDataFile]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
_cells = [[unarchiver decodeObjectForKey:@"Board"] retain];
[unarchiver release];
[data release];
}
(void) saveDataToDisk
{
NSMutableData *data = [NSMutableData alloc];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:_cells forKey:@"Board"];
[archiver finishEncoding];
[data writeToFile:[self pathToDataFile] atomically:YES];
//[array release];
[data release];
//NSMutableData
}
(BOOL)gameDataExists
{
return [[NSFileManager defaultManager] fileExistsAtPath:[self pathToDataFile]];
}
(NSString *)pathToDataFile
{
NSString *path = [[NSBundle mainBundle] bundlePath];
return [path stringByAppendingPathComponent: GAME_DAT];
}
the code above worked on simulator but failed on device.it seems like that the file can not
be found after i exit and reload my app.
And if i implement the pathToDataFile like this:
(NSString *)pathToDataFile
{
NSArray * path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *docDir = [path objectAtIndex:0];
return [docDir stringByAppendingPathComponent:GAME_DAT];
}
the file save and reload worked on device ,but the drawRect method i implemented in my view can not be called after i called [self setNeedsDisplay].
chris
Can
The bundle path is read-only on the device but read-write on the emulator. On the device any attempts to write there will therefore fail.
Your second approach to use document directory should solve the problem.
I don’t know why [self setNeedsDisplay] doesn’t work for you but it’s likely unrelated to this problem.
There is one error I noticed in your code:
Should be:
You should also release the archiver at the end of the saveDataToDisk method.