0

我正在创建一个字典列表。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];
}
4

1 回答 1

0

我做类似下面的事情。我使用键添加对象。也许这就是它不起作用的原因。

静态 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。

于 2013-05-28T18:31:00.010 回答