Best way to save to nsuserdefaults for custom class?

后端 未结 2 1073
南旧
南旧 2020-12-08 11:31

If I have a custom class Person which has three variables (which are propertized and synthesized):

NSString* theName;
float* theHeight;
int theAge;
         


        
2条回答
  •  清歌不尽
    2020-12-08 12:11

    @Brad Smith's answer is not complete, and even is incorrect in some sense. We have to use NSKeyedArchiver and NSKeyedUnarchiver as follows:

    Make your class (for example in this case Person) to conform to protocol NSCoding and implement both the methods as:

    - (id)initWithCoder:(NSCoder *)decoder {
        self = [super init];
        if(self) {
            self.name = [decoder decodeObjectForKey:];
            // as height is a pointer
            *self.height = [decoder decodeFloatForKey:];
            self.age = [decoder decodeIntForKey:];
        }
        return self;
    }
    
    - (void)encodeWithCoder:(NSCoder *)encoder {
        [encoder encodeObject:self.name forKey:];
        //as height is a pointer
        [encoder encodeFloat:*self.height forKey:]
        [encoder encodeInt:self.age forKey:];
    }
    

    Using NSUserDefaults

    // Write to NSUserDefaults
    NSData *archivedObject = [NSKeyedArchiver archivedDataWithRootObject:];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:archivedObject forKey:];
    [defaults synchronize];
    
    // Read from NSUserDefaults
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *archivedObject = [defaults objectForKey:];
     *obj = ( *)[NSKeyedUnarchiver unarchiveObjectWithData:archivedObject];
    

提交回复
热议问题