2014-04-24 115 views
0

我正在做一个简单的程序,可以存档我的对象,并在启动时取消存档。如何处理unarchiver与这种情况..?

我有一个lists.m其中可变数组采用归档称为favouritesList商店商品到文件中。内部列表,我有简单的对象称为favouriteItem

那么,问题与此代码

-(void) loadList 
{ 

self.favouritesList = 
[[NSKeyedUnarchiver unarchiveObjectWithFile:self.fileName] mutableCopy]; 
if(self.favouritesList == nil) 
    self.favouritesList = [[NSMutableArray alloc]init]; 

} 

,我已经得到唯一的例外是这个 [NSKeyedUnarchiver initForReadingWithData:]:发生了难以理解的存档( 0X62,0x70,0x6c,0×69(0x73)的,0x74,为0x30,的0x30)”

我知道我在用的文件是空的(实际上它被从包文件,这也是空的)解档复制。

那么,我怎么能避免这一点,当我仍然希望我的应用程序启动时从文件加载数据。 当我使用下面的代码

-(void) loadData { 
    self.URLLists = [NSMutableArray arrayWithContentsOfFile:self.path]; 
    if(self.URLLists == nil) { 
    self.URLLists = [[NSMutableArray alloc]init]; 
    } 

} 

这里,即使在self.path文件是空的,它返回nil,我只能说 如果它返回nil,我将指派为新一第一次。 但是,与NSkeyedUnarchiver它工作有点不同.. 你能解释它是如何不同,我如何避免这个错误..? 谢谢。

回答

2

的更简单的办法就是使用异常处理:

@try { 
      self.favouritesList = 
[[NSKeyedUnarchiver unarchiveObjectWithFile:self.fileName] mutableCopy]; 
    } 
    @catch (NSException *e) { 
      self.favouritesList = [[NSMutableArray alloc]init]; // add more code as needed 
    } 

苹果的文档是在这里。

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Exceptions/Tasks/HandlingExceptions.html#//apple_ref/doc/uid/20000059-BBCHGJIJ

+0

如何处理arrayWithContentsOfFile的情况?我不需要处理任何异常,因为它不会抛出任何异常? –

+1

@denis_choe:是的。如果您阅读[unarchiveObjectWithFile:]的文档(https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSKeyedUnarchiver_Class/Reference/Reference.html#//apple_ref/occ/clm/NSKeyedUnarchiver/unarchiveObjectWithFile :)和[arrayWithContentsOfFile:](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/clm/ NSArray/arrayWithContentsOfFile :),他们每个人都说他们如何对一个空文件做出反应。 NSKeyedUnarchiver抛出一个异常,NSArray返回nil。 – Chuck

0

,而不是试图解除存档一个空文件,你为什么不只是有文件包含一个空数组?那么你不需要任何特殊情况。

+0

你介意解释你会怎么做,请.. ..? –

+0

你的意思是让该文件与空数组在..其中..?我的意思是在viewdidload里面? –

+1

@denis_choe:我的意思是你要在这里取消存档的文件,你从你的包中复制的文件是空的。为什么不让文件包含一个空数组,而不是在你的包中存储一个空文件? – Chuck

相关问题