gpt4 book ai didi

ios - 在 iOS 中使用 RMapper 库从对象文件中获取值

转载 作者:行者123 更新时间:2023-11-29 00:39:56 24 4
gpt4 key购买 nike

我用过RMMapper库

导入文件

#import "NSUserDefaults+RMSaveCustomObject.h"

MyCart *cart = [[MyCart alloc]init];
cart.ProdCode = code;
cart.ProdName = s;
cart.Price = [NSString stringWithFormat:@"%f",tot];
cart.Quantity = quantity.text;
cart.Image = _imageProd;
NSMutableArray *array = [[NSUserDefaults standardUserDefaults] rm_customObjectForKey:@"cart"];
[array addObject:cart];

在其他页面上,我想检索存储在对象文件中的值。

我如何获得该值?

谁能帮我解决这个问题?

最佳答案

由于您要将自定义模型对象数据保存为用户默认值,因此您需要在自定义对象中实现 encodeWithCoderinitWithCoder 方法。同样,在保存时使用 archivedDataWithRootObject,在获取时使用 unarchiveObjectWithData

只需将这两个方法(encodeWithCoderinitWithCoder)放入您的 MyCart.m

- (void)encodeWithCoder:(NSCoder *)encoder {
//Encode properties, other class variables, etc
[encoder encodeObject:self.ProdCode forKey:@"ProdCode"];
[encoder encodeObject:self.ProdName forKey:@"ProdName"];
[encoder encodeObject:self.Price forKey:@"Price"];
[encoder encodeObject:self.Quantity forKey:@"Quantity"];
[encoder encodeObject:self.ImageName forKey:@"ImageName"];
}

- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
//decode properties, other class vars
self.ProdCode = [decoder decodeObjectForKey:@"ProdCode"];
self.ProdName = [decoder decodeObjectForKey:@"ProdName"];
self.Price = [decoder decodeObjectForKey:@"Price"];
self.Quantity = [decoder decodeObjectForKey:@"Quantity"];
self.ImageName = [decoder decodeObjectForKey:@"ImageName"];
}
return self;
}

然后以下代码将展示如何从 NSUserDefault 保存和获取数据

我要保存的代码:

- (void)saveCart
{
MyCart *cart = [[MyCart alloc]init];
cart.ProdCode = @"123";
cart.ProdName = @"Name";
cart.Price = [NSString stringWithFormat:@"%f",100.0];
cart.Quantity = @"20";
cart.ImageName = @"image url";

NSArray *arrayTemp = [[NSUserDefaults standardUserDefaults] objectForKey:@"cart"];

// You can not use the arrayTemp to add object as the return type from `NSUserDefault` is `NSArray` which is immutable, so use another mutable array and add the object like this
NSMutableArray *array = [NSMutableArray array];

if([arrayTemp count])
{
[array addObjectsFromArray:arrayTemp];
}

NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:cart];
[array addObject:encodedObject];
[[NSUserDefaults standardUserDefaults] setObject:array forKey:@"cart"];
[[NSUserDefaults standardUserDefaults] synchronize];

}

我要获取的代码:

- (void)getCart
{
NSMutableArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"cart"];

for (NSData *encodedObject in array) {

MyCart *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];

NSLog(@"cart ImageName %@", object.ImageName);
}
}

希望对您有所帮助。

快乐编码...

关于ios - 在 iOS 中使用 RMapper 库从对象文件中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39761737/

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