在NSUserDefaults中存储自定义对象

时间:2017-04-05 05:39:05

标签: ios objective-c nsuserdefaults nskeyedarchiver nskeyedunarchiver

我正在尝试按如下方式存储自定义对象,但是我收到错误。

// store data
NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:pOrderElements.count];
for (id orderObject in pOrderElements) {
    NSData *personEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:orderObject];
    [archiveArray addObject:personEncodedObject];
}

NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
[userData setObject:archiveArray forKey:@"personDataArray"];


// retrive data
NSData *data = [userData objectForKey:@"personDataArray"];
// the following line throws an error
id retrieveData = [NSKeyedUnarchiver unarchiveObjectWithData:data];

这是我的pOrderElements

(lldb) po pOrderElements
<__NSArrayM 0x174256b90>(
{
    category = 1;
    imagePath = "products/chicken-kabob.png";
    name = "Baked Chicken";
    price = "5.49";
}
)
  

由于未捕获的异常而终止应用   &#39; NSInvalidArgumentException&#39;,原因:&#39; - [__ NSCFArray字节]:   无法识别的选择器发送到实例0x174264f40&#39;

2 个答案:

答案 0 :(得分:2)

您取消归档不正确的对象。您将NSArray存储到NSUserDefaults

NSArray * archiveArray = [userData objectForKey:@"personDataArray"];
for (NSData *personEncodedObject in archiveArray) {
    id personObject = [NSKeyedUnarchiver unarchiveObjectWithData:personEncodedObject];
}

答案 1 :(得分:1)

首先创建自定义类,如下所示。

CustomObject.h

#import <Foundation/Foundation.h>

@interface CustomObject : NSObject

@property(strong,nonatomic)NSString *name;

@end 

CustomObject.m

#import "CustomObject.h"

@implementation CustomObject



- (void)encodeWithCoder:(NSCoder *)encoder {
    //Encode properties, other class variables, etc
    [encoder encodeObject:self.name forKey:@"name"];

}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        //decode properties, other class vars
        self.name = [decoder decodeObjectForKey:@"name"];

    }
    return self;
}

然后创建CustomObject类对象并存储在NSUserDefaults

像这样存储你的对象

CustomObject *object =[CustomObject new];
object.name = @"test";

NSMutableArray *arr = [[NSMutableArray alloc]init];
[arr  addObject:object];

NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:arr];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:encodedObject forKey:@"storeObject"];
[defaults synchronize];

NSUserDefaults获取自定义对象

NSData *storedEncodedObject = [defaults objectForKey:@"storeObject"];
    NSArray *arrStoreObject = [NSKeyedUnarchiver unarchiveObjectWithData:storedEncodedObject];
    for (int i=0; i<arrStoreObject.count; i++)
    {
        CustomObject *storedObject = [arrStoreObject objectAtIndex:i];
        NSLog(@"%@",storedObject.name);

    }