在我的模态对象中有两个值 我正试图存储在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中,然后从中查找。任何人都可以帮助我。
答案 0 :(得分:1)
试试这个.. 创建一个类&#34; CollectionModelManager.h和.m&#34;
//对于Save 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];
}
// For Get 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;
}