gpt4 book ai didi

iphone - 覆盖保存在 NSUserDefaults 中的值

转载 作者:行者123 更新时间:2023-11-28 18:25:31 25 4
gpt4 key购买 nike

我用这个方法来保存一个名为 myWallet 的可变数组,其中包含类卡片的实例。

- (void)saveMyWallet
{

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

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

[defaults synchronize];
}

我拥有的 Card 类具有三个实例变量: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

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

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

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

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

最佳答案

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

关于iphone - 覆盖保存在 NSUserDefaults 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10493945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com