I apologize for duplicate Question . I am new in ios . I want to store custom objects in userdefaults. I am using objective-c .
Thanks in advance
I apologize for duplicate Question . I am new in ios . I want to store custom objects in userdefaults. I am using objective-c .
Thanks in advance
First you create custom class Like below.
CustomObject.h
#import <Foundation/Foundation.h>
@interface CustomObject : NSObject<NSCoding>
@property(strong,nonatomic)NSString *name;
@end
CustomObject.m
#import "CustomObject.h"
@implementation CustomObject
- (void)encodeWithCoder:(NSCoder *)encoder {
//Encode properties, other class variables, etc
[encoder encodeObject:self.name forKey:@"name"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
//decode properties, other class vars
self.name = [decoder decodeObjectForKey:@"name"];
}
return self;
}
Then create CustomObject class object and store in NSUserDefaults
Stored your object like this
CustomObject *object =[CustomObject new];
object.name = @"test";
NSMutableArray *arr = [[NSMutableArray alloc]init];
[arr addObject:object];
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:arr];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:encodedObject forKey:@"storeObject"];
[defaults synchronize];
get custom object from NSUserDefaults like this
NSData *storedEncodedObject = [defaults objectForKey:@"storeObject"];
NSArray *arrStoreObject = [NSKeyedUnarchiver unarchiveObjectWithData:storedEncodedObject];
for (int i=0; i<arrStoreObject.count; i++)
{
CustomObject *storedObject = [arrStoreObject objectAtIndex:i];
NSLog(@"%@",storedObject.name);
}
In Swift 3
// set a value for key
let encodedData = NSKeyedArchiver.archivedData(withRootObject: #YOUR OBJECT#)
UserDefaults.standard.set(encodedData, forKey: #YOUR KEY#)
// retrieving a value for a key
if let data = UserDefaults.standard.data(forKey: #YOUR KEY#),
let obj = NSKeyedUnarchiver.unarchiveObject(with: data) as? #YOUR OBJECT# {
} else {
print("There is an issue")
}