覆盖NSUserDefaults中保存的值

时间:2012-05-08 06:48:56

标签: iphone ios xcode nsuserdefaults

我有这个方法来保存一个名为myWallet的可变数组,该数组包含Class Card的实例。

- (void)saveMyWallet
{

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:self.myWallet] forKey:@"myWalletArray"];

    [defaults synchronize];
}

我所拥有的Card Class有三个实例变量:name,pin和points。到目前为止,在UserDefaults中保存卡的新实例是可以的。我想知道一些关于如何覆盖点值的建议,因为当我继续计算点数时,我想更新它。

这是我的卡类

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

最后,这里是委托方法,通过该方法,点的新值(名为resulPoints)应该来自。

- (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); 
}

轰炸我提出建议:)提前致谢!

2 个答案:

答案 0 :(得分:6)

从我看到的,您实际上将对象保存为NSData,因此逻辑方法是从用户默认值中取回它,取消归档,更新属性,将其归档并将其保存回用户默认值。

答案 1 :(得分:0)

将NSUserDefaults中的数据恢复到运行时,删除键的前一个对象并写回更新的值。