2016-09-19 5 views
-1

In meinem Modal-Objekt sind zwei Werte Ich versuche, in NSUserDefaults zu speichern. Dies ist mein CodeSpeichern von NSobject-Daten in Nsuserdefaults

Interface File:

@interface collectionModel : NSObject <NSCoding> { 
} 


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

Implementierungsdatei:

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

Hier möchte ich diese ParseCollectionArr in NSUserDefaults speichern und retrive von it.can kann mir helfen.

+0

Mögliche doppelte Get von [So speichern Sie NSMutablearray in NSUserDefaults] (http://stackoverflow.com/questions/19634426/how-to-save-nsmutablearray-in-nsuserdefaults) –

+0

Auch pls beziehen sich auf http: // stackove rflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults –

+0

Folgen @ Teja Nandamuri vorgeschlagener Link –

Antwort

0

dies versuchen .. Erstellen Sie eine Klasse wie "CollectionModelManager.h und .m"

// Für Speichern 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]; 
} 

// Für 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; 
} 
Verwandte Themen