繁体   English   中英

创建字典plist数组

[英]Creating an array of dictionaries 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];
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM