Store Custom Objects in NSUserDefaults

后端 未结 2 2021
你的背包
你的背包 2021-01-23 22:15

I am trying to store a custom objects as follows, but I am getting an error.

// store data
NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:p         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-23 23:08

    First you create custom class Like below.

    CustomObject.h

    #import 
    
    @interface CustomObject : NSObject
    
    @property(strong,nonatomic)NSString *name;
    
    @end 
    

    CustomObject.m

    #import "CustomObject.h"
    
    @implementation CustomObject
    
    
    
    - (void)encodeWithCoder:(NSCoder *)encoder {
        //Encode properties, other class variables, etc
        [encoder encodeObject:self.name forKey:@"name"];
    
    }
    
    - (id)initWithCoder:(NSCoder *)decoder {
        if((self = [super init])) {
            //decode properties, other class vars
            self.name = [decoder decodeObjectForKey:@"name"];
    
        }
        return self;
    }
    

    Then create CustomObject class object and store in NSUserDefaults

    Stored your object like this

    CustomObject *object =[CustomObject new];
    object.name = @"test";
    
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    [arr  addObject:object];
    
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:arr];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:encodedObject forKey:@"storeObject"];
    [defaults synchronize];
    

    get custom object from NSUserDefaults like this

    NSData *storedEncodedObject = [defaults objectForKey:@"storeObject"];
        NSArray *arrStoreObject = [NSKeyedUnarchiver unarchiveObjectWithData:storedEncodedObject];
        for (int i=0; i

提交回复
热议问题