Hello guys,
Im willing to overwrite a custom object in NSUserDefault, it's a Matrix.
It works fine the first time I create the object and save it, but it never updates.
here's the code:
The modification to the Matrix Class
Code:
- (void)encodeWithCoder:(NSCoder *)encoder
{
//Encode properties, other class variables, etc
[encoder encodeObject:self.matriz forKey:@"matriz"];
}
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if( self != nil )
{
//decode properties, other class vars
self.matriz = [decoder decodeObjectForKey:@"matriz"];
}
return self;
}
The methods that I use in a ViewController to set up a Matrix Object named "horarios"
I want to create a new Matrix if it's the very first time I execute this ViewController or then load the previous one.
Code:
-(void)viewDidLoad(){
if([self loadCustomObjectWithKey:@"horarios"] == nil){
//Inicializar el horarios a 0, que es lo que vale al inicio
self.horarios = [[Matriz alloc]init:(int)3 column:5];
}
else{
self.horarios = [self loadCustomObjectWithKey:@"horarios"];
}
This is the code that saves and loads the customObject from NSUserDefaults in the ViewController
Code:
-(void)saveCustomObject:(Matriz*)obj
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:obj];
//[obj showValue];
[defaults setObject:myEncodedObject forKey:@"horarios"];
}
-(Matriz*)loadCustomObjectWithKey:(NSString*)key{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [defaults objectForKey: key];
Matriz* obj = (Matriz*)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];
return obj;
}
The code works fine the first time, when in NSUserDefaults there's no custom object, when I save it saves the current status of the matrix, but the next times, when there already an object if always loads the previous one, as if it could only save once the object.
I dont understand it, any ideas?