自定義對象的本地化存儲

一、首先該對象須要遵照NSCoding協議 二、直接上代碼code

//歸檔
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.type forKey:@"type"];
    [aCoder encodeObject:self.id forKey:@"id"];
    [aCoder encodeObject:self.createDate forKey:@"createDate"];
    [aCoder encodeObject:self.content forKey:@"content"];
    [aCoder encodeObject:self.modifyDate forKey:@"modifyDate"];
    [aCoder encodeObject:self.sendType forKey:@"sendType"];
    [aCoder encodeObject:self.title forKey:@"title"];
    [aCoder encodeObject:@(self.isNewMessage) forKey:@"isNewMessage"];
}
//解檔
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
        self.type = [aDecoder decodeObjectForKey:@"type"];
        self.id = [aDecoder decodeObjectForKey:@"id"];
        self.createDate = [aDecoder decodeObjectForKey:@"createDate"];
        self.content = [aDecoder decodeObjectForKey:@"content"];
        self.modifyDate = [aDecoder decodeObjectForKey:@"modifyDate"];
        self.sendType = [aDecoder decodeObjectForKey:@"sendType"];
        self.title = [aDecoder decodeObjectForKey:@"title"];
        self.isNewMessage = [[aDecoder decodeObjectForKey:@"isNewMessage"] boolValue];
    }
    return self;
}

三、保存對象

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"messages.data"];
    BOOL isTrueWrite = [NSKeyedArchiver archiveRootObject:messagesData toFile:filePath];

四、讀取string

NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
                for (MessageModel *model in arr) {
                    NSLog(@"%@",model.title);
                }
相關文章
相關標籤/搜索