NSUserDefault使用NSMutableArray存储自定义对象的NSArray

时间:2013-11-18 06:35:37

标签: ios nsmutablearray nsarray nsuserdefaults nscoding

我已经看到了关于如何将自定义对象存储到NSUserDefault内的数组的好例子。我的问题是,如果我的自定义对象有一个数组作为其属性,我该怎么做呢。

我看了一个给我这个的例子,但课程是NSMutableArray。

@implementation ClassNames
@synthesize courses;
@synthesize name;


- (void)encodeWithCoder:(NSCoder *)coder;
{
    [coder encodeObject:courses forKey:@"courses"];
    [coder encodeObject:name forKey:@"name"];
}

- (id)initWithCoder:(NSCoder *)coder;
{
    self = [super init];
    if (self != nil)
    {
        courses = [coder decodeObjectForKey:@"courses"] ;
        name = [coder decodeObjectForKey:@"name"] ;
    }
    return self;
}
@end

当我想保存和加载类

时,这就是我所说的
- (NSMutableArray *)loadClasses{
    NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
    NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:@"classes"];
    if (dataRepresentingSavedArray != nil)
    {
        NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
        if (oldSavedArray != nil)
            return [[NSMutableArray alloc] initWithArray:oldSavedArray];
        else
            return [[NSMutableArray alloc] init];
    }
    return nil;

 }




- (void)saveClasses:(ClassNames *)classes
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

    [standardUserDefaults setObject:[NSKeyedArchiver archivedDataWithRootObject:classes] forKey:@"classes"];
    [standardUserDefaults synchronize];

}

ClassNames中的NSMutableArray“courses”是NSStrings的NSMutableArray。

谢谢。

1 个答案:

答案 0 :(得分:0)

  NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  NSString *filename = [docsPath stringByAppendingPathComponent:@"test"];   

 //store the array

 [NSKeyedArchiver archiveRootObject:myArray toFile:filename];

//get the array

 NSMutableArray* myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:filename];