2016-09-19 91 views
-1

在我的模態對象中有兩個值 我試圖存儲在NSUserDefaults中。這是我的代碼將NSobject數據存儲到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

可能的複製[如何在NSUserDefaults中保存NSMutablearray](http://stackoverflow.com/questions/19634426/how-to-save-nsmutablearray-in-nsuserdefaults) –

+0

另請參考http:// stackove rflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults –

+0

按照@Teja Nandamuri建議鏈接 –

回答

0

試試這個.. 創建像 「CollectionModelManager.h和.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; 
} 
相關問題