编码NSMutableArray

时间:2013-03-24 16:24:26

标签: objective-c cocoa nsmutablearray nscoding

编辑:好的我决定将数组保存在userDefaults中...应该很简单,对吧? 保存:

NSUserDefaults *userDefs = [NSUserDefaults standardUserDefaults];
    [userDefs setObject:videoArray forKey:@"dataArray"];
    [userDefs synchronize];

负载:

 NSUserDefaults *userDefs = [NSUserDefaults standardUserDefaults];
    videoArray = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"dataArray"];

    [tableview reloadData];
    NSLog(@"%@",videoArray);

数组中对象的类:

@interface DEVideoModel : NSObject

@property (copy) NSString *name;
@property (copy) NSImage *thumbnail;
@property (copy) NSDictionary *qualities;
@property (readwrite) float videoSize;
@property (readwrite) float progress;
@property (copy) NSString *filePath;
@property (copy) NSDate *datum;


@end

@synthesize name,filePath,videoSize,qualities,thumbnail,datum,progress;
-(id)init {
    self = [super init];
    if(self) {
        qualities = [[NSDictionary alloc]init];
        thumbnail = [[NSImage alloc]init];
    }
    return self;
}


@end

当我加载它时,我的videoArray是(null)?我不明白。顺便说一下,videoArray是一个NSMutableArray而不是NSArray。

1 个答案:

答案 0 :(得分:2)

在您的代码中,您正在将NSData写入NSCoder,因此您需要读取NSData,然后将其转换为Array。

NSURL *appSupportDir = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
NSString *path = [NSString stringWithFormat:@"%@/DEConvert.dat",[appSupportDir path]];
NSLog(@"%@",appSupportDir);
NSData *data = [NSData dataWithContentsOfFile:path];
NSMutableArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:data];

在NSUserDefault中存储对象

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"your key"];

Unarchiving也很简单:

NSData *NewData = [[NSUserDefaults standardUserDefaults] objectForKey:@"your key"];
NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:NewData];