How to save custom objects in array and store it in NSUserDefaults - iPhone

前端 未结 3 659
星月不相逢
星月不相逢 2020-12-10 09:32

I am getting my custom class object after button action method. Now I need to store multiple custom objects in NSMutableArray and then store this array in

相关标签:
3条回答
  • 2020-12-10 09:59

    To store and retrieve array with custom object on user defaults you can use following methods:

    -(void)writeArrayWithCustomObjToUserDefaults:(NSString *)keyName withArray:(NSMutableArray *)myArray
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myArray];
        [defaults setObject:data forKey:keyName];
        [defaults synchronize];
    }
    
    -(NSArray *)readArrayWithCustomObjFromUserDefaults:(NSString*)keyName
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSData *data = [defaults objectForKey:keyName];
        NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [defaults synchronize];
        return myArray; 
    }
    

    But make sure you have implemented

    - (void) encodeWithCoder : (NSCoder *)encode ;
    - (id) initWithCoder : (NSCoder *)decode;
    

    method in data model class to avoid crash as followings:

    - (void)encodeWithCoder:(NSCoder *)coder;
    {
        [coder encodeObject:label forKey:@"label"];
        [coder encodeInteger:numberID forKey:@"numberID"];
    }
    
    - (id)initWithCoder:(NSCoder *)coder;
    {
        self = [super init];
        if (self != nil)
        {
            label = [[coder decodeObjectForKey:@"label"] retain];
            numberID = [[coder decodeIntegerForKey:@"numberID"] retain];
        }   
        return self;
    }
    
    0 讨论(0)
  • 2020-12-10 10:05

    This two methods will mainly used to store and retrieve custom object's property.

    - (void)encodeWithCoder:(NSCoder *)encoder ;
    - (id)initWithCoder:(NSCoder *)decoder;
    

    Take look at @chrissr's answer, @Brad Larson's answer

    0 讨论(0)
  • 2020-12-10 10:23

    You need to archive it by implementing NSCoding protocol. Then you can write it to any file.

    Implement these methods in your model :

    - (void) encodeWithCoder : (NSCoder *)encode ;
    - (id) initWithCoder : (NSCoder *)decode;
    

    As you say, you have implemented this in the Class, now you need to save the array.

    For saving and reading the array, you need to use :;

    [[NSUserDefaults standardUserDefaults] setObject:yourMutableArray forKey:@"keyForArray"];
    NSMutableArray *array = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"keyForArray"]];
    
    0 讨论(0)
提交回复
热议问题