创建一个字典数组plist

时间:2013-05-28 17:37:10

标签: iphone ios objective-c cocoa-touch plist

我正在创建一个字典的plist。 plist从空开始,然后我这样做:

NSMutableArray *favouritesList = [[NSMutableArray alloc] initWithContentsOfFile:path];
[favouritesList addObject:thisPlace]; // where thisPlace is some NSDictionary
[favouritesList writeToFile:path atomically:YES];

当我马上做的时候:

NSArray *savedFav = [[NSArray alloc] initWithContentsOfFile:path];
NSLog(@"%@", savedFav);

我得到一个空数组。为什么是这样?为什么写得不好?我正确地设置了plist,我调试了它。但我无法添加字典。

plist只是一个空的plist,其根是一个数组

修改

以下是我构建路径的方法:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"favourites.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:path]) {
    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"favourites" ofType:@"plist"];
    [fileManager copyItemAtPath:sourcePath toPath:path error:nil];
}

1 个答案:

答案 0 :(得分:0)

我做的事情如下。我使用密钥添加对象。也许这就是为什么它不起作用。

static NSMutableDictionary * dictionaryStore;

+(void)initialize{
    if(dictionaryStore == nil){
        dictionaryStore = [[NSMutableDictionary alloc] initWithContentsOfFile:[self getFilePath]];
        if(dictionaryStore == nil)
            dictionaryStore = [NSMutableDictionary new];
    }
}

+(NSString *)getFilePath{
    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *plistPath = [rootPath stringByAppendingPathComponent:@"filename.plist"];
    return plistPath;
}

+(NSString *)getValueForKey:(NSString *)key{
    [self initialize];

    return [dictionaryStore objectForKey:key];
}

+(void)setValue:(NSString *)value forKey:(NSString *)key{
    [self initialize];

    [dictionaryStore setValue:value forKey:key];
}

+(BOOL)save{
    [self initialize];

    return [dictionaryStore writeToFile:[self getFilePath] atomically:YES];
}

编辑: 所以为了节省价值,我做了:

[WAStore setValue:myValue forKey:myKey];
BOOL isSuccessful = [WAStore save];

WAStore是班级名称。 myValue可以是大多数数据类型(NSManagedObjectModels不起作用)。 myKey是任何NSString。