[英]Why there save and load file code works on iphone simulator but failed on device
(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. 上面的代码在模拟器上有效,但在device。上失败。我退出并重新加载应用后,似乎找不到该文件。 And if i implement the pathToDataFile like this:
如果我像这样实现pathToDataFile:
(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]. 文件保存和重新加载在设备上工作,但是在调用[self setNeedsDisplay]之后无法调用在视图中实现的drawRect方法。
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. 我不知道为什么[self setNeedsDisplay]对您不起作用,但可能与该问题无关。
There is one error I noticed in your code: 我在您的代码中发现了一个错误:
NSMutableData *data = [NSMutableData alloc];
Should be: 应该:
NSMutableData *data = [[NSMutableData alloc] init];
You should also release the archiver at the end of the saveDataToDisk method. 您还应该在saveDataToDisk方法的末尾释放存档程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.