2013-05-28 73 views
0

我正在創建一個字典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]; 
} 
+0

你記錄了'path'以確認它是有效的嗎?它是否指向'Documents'目錄中的文件?你是如何構建'路徑'的?你檢查了'writeToFile'是否返回了'TRUE'? – Rob

+0

是的,請參閱編輯我如何製作路徑 – darksky

+1

如果plist文件爲空,則第一次初始化失敗並返回'nil'。你必須檢查並分配 - 初始化一個有效但空的數組。 – 2013-05-28 17:42:05

回答

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。