确保您尝试归档的任何类都实现了 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