最近用了一下归档保存,很简单的应用,就是把一个数组归档保存到沙盒,在模拟器上跑起来是没问题的,可是运行到真机上连接xcode测试就是归档失败,废话少说,直接说解决办法,Google了一下,直接导向了stackoverflow了:
本人源代码如下:
//归档保存搜索历史记录muArrayFindHistory,一旦离开这个页面,立即归档保存记录
NSString *localPath = @"muArrayFindHistory.src";
NSString * pathMuArrayFindHistory = [NSHomeDirectory() stringByAppendingPathComponent:localPath];
BOOL success = [NSKeyedArchiver archiveRootObject:self.muArrayFindHistory toFile:pathMuArrayFindHistory];
此处success在模拟器上返回是YES,在真机上返回时NO,
解决办法:
//归档保存搜索历史记录muArrayFindHistory,一旦离开这个页面,立即归档保存记录
NSString *localPath = @"Documents/muArrayFindHistory.src";
NSString * pathMuArrayFindHistory = [NSHomeDirectory() stringByAppendingPathComponent:localPath];
BOOL success = [NSKeyedArchiver archiveRootObject:self.muArrayFindHistory toFile:pathMuArrayFindHistory];
这样制定一下路径成功了.
stackoverflow上的疑问与解答:
原文网址:http://stackoverflow.com/questions/963175/nskeyedarchiver-works-in-iphone-simulator-fails-on-device
大概意思是说在模拟器上只要在沙盒中给定了路径就可以,可是在真机上需要更明确一下.
I've got a simple app that's trying to save some data between invocations using NSKeyedArchiver/NSKeyedUnarchiver. It works fine on the simulator, but when I export it to real iPhone hardware, NSKeyedArchiver fails to be able to write to disk.
I'm using the class method
[NSKeyedArchiver archiveRootObject:myRootObject toFile:@"data.archive"]
All my objects in 'myRootObject' implement the NSCoding protocol. Again, on the simulator, this returns YES and everything's good. On the device, this returns NO and nothing has saved. (Both are 2.2.1)
Is there some write permission or something an app needs to be able to write to the phone's HD? Anybody already seen this?
Thanks for your help in advance.
回答
I'm guessing here but wouldn't you specify file path pointing to directory within your bundle? I think you can write to Documents directory under your NSBundle.
Try creating the file path like this:
// Documents directory
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
// <Application Home>/Documents/foo.arch
NSString *fooPath =
[documentsPath stringByAppendingPathComponent:@“foo.arch”];
And then pass "fooPath" as the path to your file in the method you're using, see if that helps.
Thanks for your help you sent me down the right path of thought.... the trick was to figure out the application's root dir, and write to a subdir of that. annoying that the simulator let's you write anywhere.
Here's what fixed all:
NSString *localPath = @"Documents/my.archive";
NSString *fullPath = [NSHomeDirectory() stringByAppendingPathComponent:localPath];
[NSKeyedArchiver archiveRootObject:archive toFile:fullPath];
See also this similar thread