-1

In My Modal Object two values are there I'm trying to store in NSUserDefaults. This is My Code

interface File:

@interface collectionModel : NSObject <NSCoding> {
}


@property(nonatomic,retain) NSString *name;
@property(nonatomic,retain) NSString *author;

Implementation File:

@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);

Here I want to store this parsedCollectionArr in NSUserDefaults and retrive from it.can any one help me.

1 Answers1

1

try this.. Create a class like "CollectionModelManager.h and .m"

//For 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;
}