使用NSMutableDictionary保存数据

时间:2011-03-06 14:31:02

标签: objective-c nsmutabledictionary

我有一种将dic保存到磁盘的方法:

+(BOOL) writeApplicationData:(NSDictionary *)data 
              bwriteFileName:(NSString *)fileName
{
    NSLog(@"writeApplicationData");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    if (!documentsDirectory) {
        NSLog(@"Documents directory not found!");
        return NO;
    }
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
    return ([data writeToFile:appFile atomically:YES]);
}

我测试了它:

        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        NSMutableDictionary *d1 = [[NSMutableDictionary alloc] init];
        NSMutableDictionary *d2 = [[NSMutableDictionary alloc] init];

        [d1 setObject:@"d11"
               forKey:@"d11"];
        [d1 setObject:@"d12"
               forKey:@"d12"];
        [d1 setObject:@"d13"
               forKey:@"d13"];

        [d2 setObject:@"d21"
               forKey:@"d21"];
        [d2 setObject:@"d22"
               forKey:@"d22"];
        [d2 setObject:@"d23"
               forKey:@"d23"];

        [dic setObject:d1
                forKey:@"d1"];
        [dic setObject:d2
                forKey:@"d2"];

        [self writeApplicationData:dic
                    bwriteFileName:@"testSave"];

数据保存正确。

然后我尝试用类obj保存d1:

LevelInfoData *levelInfoData = [[LevelInfoData alloc] init];

[levelInfoDictionary setObject:levelInfoData
            forKey:@"test"];

[dic setObject:levelInfoDictionary
        forKey:@"LevelInfoDictionary"];

但这一次,即使磁盘中没有生成plist文件。

这是LevelInfoData类:

@interface LevelInfoData : NSObject {

    int levelNum;
}

@property (nonatomic) int levelNum;

@end

@implementation LevelInfoData
@synthesize levelNum;
@synthesize isLevelLocked;
@synthesize isLevelCleared;
@synthesize levelHighScore;

-(id)init
{  
    if( (self = [super init]) ) {

        levelNum = 0;
    }

    return self;
}

@end

我真的很困惑,希望有人可以帮助我,谢谢。

2 个答案:

答案 0 :(得分:3)

字典的内容需要是属性列表类型对象。

来自NSDictionary类参考:

此方法在写出文件之前以递归方式验证所有包含的对象是属性列表对象(NSData,NSDate,NSNumber,NSString,NSArray或NSDictionary的实例),如果所有对象都不是属性列表对象,则返回NO ,因为结果文件不是有效的属性列表。

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html

您可能想尝试使自定义类成为NSData的子类而不是NSObject。

答案 1 :(得分:1)

我不确定你对NSDictionary的依恋程度,但这可能是NSCoder更好地为你服务的情况。

请参阅nscoder vs nsdictionary when do you use what

此处有更多详情: