将 NSobject 数据存储到 Nsuserdefaults
Posted
技术标签:
【中文标题】将 NSobject 数据存储到 Nsuserdefaults【英文标题】:store NSobject data into Nsuserdefaults 【发布时间】:2016-09-19 14:37:34 【问题描述】:在我的模态对象中有两个值 我正在尝试存储在 NSUserDefaults 中。这是我的代码
接口文件:
@interface collectionModel : NSObject <NSCoding>
@property(nonatomic,retain) NSString *name;
@property(nonatomic,retain) NSString *author;
实施文件:
@implementation collectionModel
@synthesize name = _name;
@synthesize author = _author;
- (id)initWithCoder:(NSCoder *)aDecoder
if (self = [super init])
self.name = [aDecoder decodeObjectForKey:@"name"];
self.author = [aDecoder decodeObjectForKey:@"author"];
return self;
- (void)encodeWithCoder:(NSCoder *)aCoder
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeObject:_author forKey:@"author"];
ViewController.M
#import "collectionModel.h"
parsedCollectionArr = [[NSMutableArray alloc] init];
for (NSDictionary *obj in collectionBalk)
NSString * Name = [obj objectForKey:@"Name"];
NSString * author = [obj objectForKey:@"author"];
collectionModel *dataObj = [[collectionModel alloc] init];
dataObj.name = Name;
dataObj.author = author;
[parsedCollectionArr addObject:dataObj];
NSLog(@"parsedCollectionArr count ---->>>> %d",23);
在这里,我想将这个 parsedCollectionArr 存储在 NSUserDefaults 中并从中检索。任何人都可以帮助我。
【问题讨论】:
How to save NSMutablearray in NSUserDefaults的可能重复 也请参考***.com/questions/2315948/… 关注@Teja Nandamuri 建议的链接 @KuntalGajjar。你可以,使用 NSCoding。 【参考方案1】:试试这个.. 创建一个类似“CollectionModelManager.h and .m”的类
//用于保存CollectionModel
+ (void)saveCollectionModel:(CollectionModel *) collectionModel
NSData *encodedData = [NSKeyedArchiver archivedDataWithRootObject:collectionModel];
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
[userDef setObject:encodedData forKey:kCollectionModelKey]; //here kCollectionModelKey is a static string
[userDef synchronize];
//获取CollectionModel
+ (CollectionModel *)getCollectionModel
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
CollectionModel *collectionModel = nil;
NSData *encodedData = [userDef objectForKey:kCollectionModelKey]; //Same static string use here kCollectionModelKey
if (encodedData != nil)
collectionModel = [NSKeyedUnarchiver unarchiveObjectWithData:encodedData];
return collectionModel;
【讨论】:
以上是关于将 NSobject 数据存储到 Nsuserdefaults的主要内容,如果未能解决你的问题,请参考以下文章
将数据从 ViewController 传递到 NSObject