iOS对象从头开始存档

我正在研究一个iOS应用程序,涉及到保存和检索一个NSMutableArray,其中包含一个自定义对象的多个实例。 我已经看过几个指导,如苹果的文档

我得到了如何做到这一点(我认为),似乎我不得不使用归档,因为我的数组中的对象不是原始variables,因此我已经使我的对象NSCoding兼容。 不过,我也看到使用NSDefaults或任何我不明白的例子(我没有文件IO经验)。 在看到所有这些信息之后,我很难将所有东西拼凑在一起。 所需要的是一个完整的从开始到结束的示例程序的指南,它成功地使用归档来保存和检索自定义对象(在数组中)。 如果有人能指出一个很好的指导,或者在这个post上自己做,那将是非常感谢! 谢谢大家,堆栈溢出是一个很棒的地方!

PS如果需要更多信息,请在评论中告诉我!

确保你要存档的任何类实现了NSCoding协议,然后执行如下操作:

@interface MyClass<NSCoding> @property(strong,nonatomic) NSString *myProperty; @end @implementation MyClass #define myPropertyKey @"myKey" -(id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if( self != nil ) { self.myProperty = [aDecoder decodeObjectForKey:myPropertyKey]; } return self; } -(void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:[self.myProperty copy] forKey:myPropertyKey]; } @end 

然后我使用一个名为FileUtils的类来完成我的归档工作:

 @implementation FileUtils + (NSObject *)readArchiveFile:(NSString *)inFileName { NSFileManager *fileMgr = [NSFileManager defaultManager]; NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectoryPath, inFileName]; NSObject *returnObject = nil; if( [fileMgr fileExistsAtPath:filePath] ) { @try { returnObject = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; } @catch (NSException *exception) { returnObject = nil; } } return returnObject; } + (void)archiveFile:(NSString *)inFileName inObject:(NSObject *)inObject { NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectoryPath, inFileName]; @try { BOOL didSucceed = [NSKeyedArchiver archiveRootObject:inObject toFile:filePath]; if( !didSucceed ) { NSLog(@"File %@ write operation %@", inFileName, didSucceed ? @"success" : @"error" ); } } @catch (NSException *exception) { NSLog(@"File %@ write operation threw an exception:%@", filePath, exception.reason); } } + (void)deleteFile:(NSString *)inFileName { NSFileManager *fileMgr = [NSFileManager defaultManager]; NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectoryPath, inFileName]; NSError *error; if ( [fileMgr fileExistsAtPath:filePath] && [fileMgr removeItemAtPath:filePath error:&error] != YES) { NSLog(@"Unable to delete file: %@", [error localizedDescription]); } } @end