您好,登錄后才能下訂單哦!
對象歸檔的定義:
對象歸檔就是將對象歸檔以文件的形式保存到磁盤中,使用的時候以該文件保存的路徑讀取文件中的內容
使用NSKeyedArichiver進行歸檔、NSKeyedUnarchiver進行接檔,這種方式會在寫入、讀出數據之前對數據進行序列化、反序列化操作。
單對象歸檔,多個對象歸檔,自定義對象歸檔
常用的歸檔一般用在工具類中,對不可變的數據進行歸檔,可變的數據不進行歸檔,用起來更加方便
//1.一個對象歸檔
NSString *homeDictionary = NSHomeDirectory();//獲取根目錄
NSString *homePath = [homeDictionary stringByAppendingPathComponent:@"archiver.data"];//添加儲存的文件名
//歸檔 toFile:路徑 archiveRootObject:id對象
[NSKeyedArchiver archiveRootObject:@"對象" toFile:homePath];
//接檔
id object = [NSKeyedUnarchiver unarchiveObjectWithFile:homePath];
NSLog(@"%@",object);
//2.將多個對象歸檔
NSMutableData *data = [NSMutableData data];
//歸檔
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
int aInt = 100;
NSString *aString = @"I is an Apple";
NSDictionary *aDict = @{@"a":@"b",@"c":@"d"};
[archiver encodeObject:@(aInt) forKey:@"aInt"];
[archiver encodeObject:aString forKey:@"aString"];
[archiver encodeObject:aDict forKey:@"aDict"];
[archiver finishEncoding];
NSString *dataHomePath = [NSHomeDirectory() stringByAppendingPathComponent:@"data.archiver"];
[data writeToFile:dataHomePath atomically:YES];
//接檔
NSMutableData *muData = [[NSMutableData alloc]initWithContentsOfFile:dataHomePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:muData];
NSInteger anInt = [[unarchiver decodeObjectForKey:@"aInt"] integerValue];
NSString *anString = [unarchiver decodeObjectForKey:@"aString"];
NSDictionary *anDict = [unarchiver decodeObjectForKey:@"aDict"];
[unarchiver finishDecoding];
NSLog(@"anInt=%@,anString=%@,anDict=%@",@(anInt),anString,anDict);
//3.自定義對象歸檔實現copy協議
#import <Foundation/Foundation.h>
@interface ArchiveCopy : NSObject
@property (copy,nonatomic) NSString *name;
@property (copy,nonatomic) NSString *anAge;
end
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:@"name"];
[aCoder encodeObject:@"anAge"];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
_name = [aDecoder decodeObjectForKey:@"name"];
_anAge = [aDecoder decodeIntegerForKey:@"anAge"];
}
return self;
}
#pragma mark - NSCoping
- (id)copyWithZone:(NSZone *)zone {
ArchiveCopy *copy = [[[self class] allocWithZone:zone] init];
copy.name = [self.name copyWithZone:zone];
copy.anAge = [self.address copyWithZone:zone];
return copy;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。