0

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

- (void)saveMyWallet
{

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

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

    [defaults synchronize];
}

我拥有的 Card 类具有三个实例变量:名称、引脚和点。到目前为止,在 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

卡.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

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

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

用建议轰炸我:)提前谢谢!

4

2 回答 2

6

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

于 2012-05-08T06:53:25.470 回答
0

将 NSUserDefaults 中的数据检索到运行时,删除键的先前对象并写回更新的值。

于 2012-05-08T06:59:39.670 回答