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 NSUserDefaults
.
Here is my code :
-(IBAction)onClickSubmitLater:(id)sender
{
//Saving store in user defaults for later upload data.
NSMutableArray *arrayStoreList = [[NSMutableArray alloc] init];
arrayStoreList = [Util getArrayPreference:@"Store"];//arrayStoreList is the list of all stores.
Store *store = [[Store alloc] init];
store = [arrayStoreList objectAtIndex:self.selectedStoreIndex];//here i am getting particular store that i need to save in array.
//archive
NSData *dataStore = [NSKeyedArchiver archivedDataWithRootObject:store];
[[NSUserDefaults standardUserDefaults] setObject:dataStore forKey:@"resultStore"];
//unarchive
NSData *dataResultStore = [[NSUserDefaults standardUserDefaults] objectForKey:@"resultStore"];
Store *resultStore = (Store *)[NSKeyedUnarchiver unarchiveObjectWithData:dataResultStore];
NSLog(@"%@", resultStore);
}
Using above code, it is saving single Custom class Store
object in NSUserDefaults
. So I would like to save all Store
object in NSMutableArray
after submit later ibaction. Later, I will fetch array of stores for uploading store on server one by one.
Thanks.
To store and retrieve array with custom object on user defaults you can use following methods:
But make sure you have implemented
method in data model class to avoid crash as followings:
You need to archive it by implementing
NSCoding
protocol. Then you can write it to any file.Implement these methods in your model :
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 :;
This two methods will mainly used to
store
andretrieve
custom object's property.Take look at @chrissr's answer, @Brad Larson's answer