How to save and retrieve NSObject class using NSUserDafaults in iOS

后端 未结 2 878
名媛妹妹
名媛妹妹 2021-01-21 11:50

Hi I want to save and retrieve NSObject class using NSUserDefaults for that I wrote below code but I am getting exception like below

2条回答
  •  臣服心动
    2021-01-21 12:31

    You can set object like this:

    NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:savingbean];
    [currentDefaults setObject:data forKey:@"DATA"];
    [currentDefaults synchronize];
    

    and for get object like this:

    NSData *data = [currentDefaults objectForKey:@"DATA"];
    SavingBean *token = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    

    For Custom class you have to edit this methods in you bean class:

    - (void)encodeWithCoder:(NSCoder *)encoder
    {
        [encoder encodeObject:self.userName==nil?@"":self.userName forKey: @"userName"];
        [encoder encodeObject:self.passWord==nil?@"":self.passWord forKey: @"passWord"];
    }
    
    -(id)initWithCoder:(NSCoder *)decoder
    {
        self = [super init];
        if(self)
        {
            self.userName = [decoder decodeObjectForKey: @"userName"];
            self.passWord = [decoder decodeObjectForKey: @"passWord"];
        }
        return self;
    }
    

    Here is most voted similar answer. You can also get good stuff from there.

    You can also use JSON Accelerator to create bean class. This is very simple and powerful tool.

提交回复
热议问题