NSUserDefaults数据存储

//对于数据的存储:
//当需要存储的数据是自定义类的对象时,不管是放在NSArray或者NSDcitionary中,自定义类使用NSUserDefaults存储时,都要
//继承NSCoding协议

//SearchArticleModel.h文件
@interface SearchArticleModel : NSObject<NSCoding>{
    @property (nonatomic, assign) NSInteger top;
}

//SearchArticleModel.m文件
@implementation SearchArticleModel
- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
        self.top = [[aDecoder decodeObjectForKey:@"top"] integerValue];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:[NSString stringWithFormat:@"%ld",(long)self.top] forKey:@"top"];
}
@end

//归档和解档的实现方法
//加载最新数据后归档
//articleArr中存储数组
- (void)archiveObject{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *articleArchiveArr = [[NSMutableArray alloc] init];
    for (SearchArticleModel *recommendedAM in articleArr) {   
        NSData *recommendedObj = [NSKeyedArchiver archivedDataWithRootObject:recommendedAM];
        [articleArchiveArr addObject:recommendedObj];
    }
    [defaults setObject:articleArchiveArr forKey:@"articleArr"];
    [defaults synchronize];
}

//加载界面后解档
//数据放在articleArr数组中
- (void)unarchiveObject{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *recommendArticleModelArr = [[NSMutableArray alloc] init];
    for (NSData *data in [defaults objectForKey:@"articleArr"]) {
       SearchArticleModel *recommendArticleModel  = [[SearchArticleModel alloc] init];
       recommendArticleModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
       [articleArr addObject:recommendArticleModel];
    }
}

//附另一种解决方案 
http://www.crifan.com/store_save_array_of_custom_object_class_into_nsuserdefaults_in_iphone_ios/
http://www.crifan.com/nsuserdefaults_sometime_occasion_can_not_save_data_correctly/


你可能感兴趣的:(NSUserDefaults数据存储)