在NSUserDefaults中存储自定义对象

时间:2011-10-03 13:48:35

标签: objective-c nsmutablearray nsuserdefaults nskeyedarchiver

我正在尝试在NSUserDefaults中保存一个对象,但我还没有成功。场景是,我有一个SyncObjct类的对象syncObject。我在SyncObject类中实现了以下方法

- (NSMutableDictionary*)toDictionary;
+ (SyncObject*)getFromDictionary :(NSMutableDictionary*)dictionary;
- (id) initWithCoder: (NSCoder *)coder;
- (void) encodeWithCoder: (NSCoder *)coder;

而且SyncObject类也是NSCoding类。现在,SyncObject类包含一个名为jobsArray的NSMutableArray。此数组包含JobObject类的对象。我为这个类实现了相同的上述方法,以使其符合编码。在SyncObject类的toDictionary方法中,我通过写下面的行来将这个数组存储在字典中。

[dictionary setValue:jobsArray forKey:@"jobsArray"];

我正在通过编写以下行在SyncOject类的getFromDictionary方法中检索它。

    + (SyncObject*)getFromDictionary :(NSMutableDictionary*)dictionary 
{       
    NSLog(@"SyncObject:getFromDictionary");
    SyncObject *syncObject = [[SyncObject alloc] init];

    @try 
    {

        syncObject.noOfJobs = [[dictionary valueForKey:@"noOfJobs"] intValue];  
        syncObject.totalJobsPerformed = (TotalJobsPerformed*)[dictionary valueForKey:@"totalobsPerformed"];
        syncObject.jobsArray = [dictionary valueForKey:@"jobsArray"];

    }
    @catch (NSException * e) 
    {
        NSLog(@"EXCEPTION %@: %@", [e name], [e reason]);
    }
    @finally 
    {

    }

    return syncObject;
}

我还通过编写以下行来在NSUserDefault中存储syncObject。

NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:syncObject];
[userStorage setObject:myEncodedObject forKey:SYNC_OBJECT];

我正在通过编写以下行

从NSUserDefaults中检索对象
NSData *myEncodedObject = [userStorage objectForKey: SYNC_OBJECT];
    syncObject = (SyncObject*)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];

问题是我无法正确检索jobsArray。在尝试访问它时会返回一些无效对象并且应用程序崩溃。请问有人可以告诉我这个问题的原因吗?

最好的问候

2 个答案:

答案 0 :(得分:0)

我认为问题在于NSUserDefaults不支持存储自定义对象类型。

使用-setObject时Apple的文档:value参数只能是属性列表对象:NSData,NSString,NSNumber,NSDate,NSArray或NSDictionary。对于NSArray和NSDictionary对象,它们的内容必须是属性列表对象。

您可以直接从Apple's NSUserDefault Class Reference manual查看剩余的文档。

答案 1 :(得分:0)

  

自定义类.h

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property(nonatomic, retain) NSArray *names;

@property(strong,nonatomic)NSString *name;


@end
  

自定义类.m

 #import "Person.h"

@implementation Person
@synthesize names;


- (void)encodeWithCoder:(NSCoder *)encoder {
    [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;
}


@end
  

创建Person类对象并从NSUserDefaults

存储和检索存储的数据

存储您的对象:

#import "ViewController.h"
#import "Person.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *textBox;

@end

NSMutableArray *arr;

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)saveButton:(id)sender {
    Person *person =[Person new];
    person.name = _textBox.text;

     arr = [[NSMutableArray alloc]init];
    [arr  addObject:person];

    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:arr];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:encodedObject forKey:@"name"];
    [defaults synchronize];
}
- (IBAction)showButton:(id)sender {
    _label.text = @"";

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    NSData *storedEncodedObject = [defaults objectForKey:@"name"];
    NSArray *arrStoreObject = [NSKeyedUnarchiver unarchiveObjectWithData:storedEncodedObject];

    for (int i=0; i<arrStoreObject.count; i++)
    {
        Person *storedObject = [arrStoreObject objectAtIndex:i];

        _label.text = [NSString stringWithFormat:@"%@ %@",  _label.text , storedObject.name];

    }


}

@end