Best way to save to nsuserdefaults for custom class?

后端 未结 2 1067
南旧
南旧 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 11:54

    I find implementing encodeWithCoder and initWithCoder quite boring, especially if you have many attributes in your class, and many classes to save to NSUserDefaults.

    I create a library RMMapper (https://github.com/roomorama/RMMapper) to help save custom object into NSUserDefaults easier and more convenient.

    To mark a class as archivable, just use: #import "NSObject+RMArchivable.h"

    To save a custom object into NSUserDefaults:

    #import "NSUserDefaults+RMSaveCustomObject.h"
    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    [defaults rm_setCustomObject:user forKey:@"SAVED_DATA"];
    

    To get custom obj from NSUserDefaults:

    user = [defaults rm_customObjectForKey:@"SAVED_DATA"]; 
    

提交回复
热议问题