I have this method to save a mutable array named myWallet that contains instances of the Class Card.
- (void)saveMyWallet
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:self.myWallet] forKey:@"myWalletArray"];
[defaults synchronize];
}
The Card Class that I have has three instance variables: name, pin, and points. So far, saving new instances of the Card in UserDefaults is ok. I would just like to know some suggestions on how can I overwrite the value of points because as I proceed in the computation of points, I want to update it.
Here is my Card Class
Card.h
#import <Foundation/Foundation.h>
@interface Card : NSObject <NSCoding>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *pin;
@property (nonatomic, strong) NSNumber *points;
@property (nonatomic, strong) NSMutableArray *pointsToDeduct;
- (double) subtractPoints: (double) requiredPoints;
- (void) encodeWithCoder:(NSCoder *)coder;
- (id) initWithCoder: (NSCoder *)coder;
@end
Card.m
#import "Card.h"
@implementation Card
@synthesize name = _name;
@synthesize pin = _pin;
@synthesize points = _points;
@synthesize pointsToDeduct = _pointsToDeduct;
- (id)initWithCoder:(NSCoder *)coder
{
self = [[Card alloc] init];
if(self != nil) {
self.name = [coder decodeObjectForKey:@"name"];
self.pin = [coder decodeObjectForKey:@"pin"];
self.points = [coder decodeObjectForKey:@"points"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:self.name forKey:@"name"];
[coder encodeObject:self.pin forKey:@"pin"];
[coder encodeObject:self.points forKey:@"points"];
}
- (double) subtractPoints:(double) requiredPoints
{
double latestPoints;
latestPoints = ([self.points doubleValue] - requiredPoints);
return latestPoints;
}
@end
And lastly, here is the delegate method by which the new value of the points (named resultingPoints) should come from.
- (void)perksDetailsViewController:(PerksDetailsViewController *)sender didPassRequiredPoints:(NSNumber *)requiredPoints withCard:(Card *)selectedCard
{
double perksPoints = [requiredPoints doubleValue];
self.resultingPoints = [NSNumber numberWithDouble:[selectedCard subtractPoints:perksPoints] ];
NSLog(@"points remaining %@", self.resultingPoints);
}
Bombard me with suggestions 🙂 Thanks in advance!
From what I see, you actually save your object as NSData, so the logical approach is to get it back from the user defaults, unarchive it, update the properties, archive it and save it back to the user defaults.