2011-08-02 107 views
1

我想存儲一個NSMutableArray到一個pList,但是當我檢查我的data.plist,裏面沒有任何值。任何想法爲什麼?保存NSMutableArrays pList

-(void)run 
{ 
Global *myGlobal = [Global sharedGlobal]; 

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

NSMutableDictionary *category = [[NSMutableDictionary alloc]init]; 
NSMutableDictionary *totalCategory = [[NSMutableDictionary alloc]init]; 
for (int i = 0 ; i < [myGlobal.categoryArray count];i++){ 
    Category * c = [categoryArray objectAtIndex:i]; 

    [category setObject:c.name forKey:@"category"]; 

    [totalCategory setObject:category forKey:@"allCategory"]; 

    NSMutableDictionary *stock = [NSMutableDictionary dictionaryWithContentsOfFile:path]; 
    [stock writeToFile:path atomically:YES]; 
} 
if(totalCategory==nil){ 
    NSLog(@"failed to retrieve dictionary from disk"); 
} 
} 

回答

0

這兩行沒有意義。第一行將path中的字典讀入stock,第二行將其寫回。沒有任何內容添加到stock

NSMutableDictionary *stock = [NSMutableDictionary dictionaryWithContentsOfFile:path]; 
[stock writeToFile:path atomically:YES]; 
+0

一個例子是不是? –

+0

是真實的,但您需要將某物放入'stock'或writeToFile將不存儲任何東西。 – progrmr

0

當保存到pList時,應該試着使它像這樣。

 
[totalCategory writeToFile:path atomically:YES]; 

這是,如果我不包括行[將writeToFile]那麼它不會我的字典/陣列存儲到plist中它是如何工作正常

 

+ (void) saveParams:(int)kotuc one:(NSNumber*)one two:(NSNumber*)two three:(NSNumber*)three four:(NSNumber*)four five:(NSNumber*)five six:(NSNumber*)six seven:(NSNumber*)seven eight:(NSArray*)eight{ 

    NSString *path = [self getNSPath]; 
    NSDictionary* dw = [[NSDictionary alloc] initWithContentsOfFile:path]; 
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; 

    NSArray *keys = [[NSArray arrayWithObjects:@"one", @"two", @"three", @"four", @"five", @"six",@"seven", @"eight",nil] retain]; 
    NSArray *objects = [[NSArray arrayWithObjects:one, two, three, four, five, six, seven, eight, nil] retain]; 


    NSMutableDictionary *subDict = [[NSMutableDictionary alloc] initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys]; 


    ////save old 
    [dict setDictionary:dw]; 
    ////save new 
    [dict setObject:subDict forKey:[NSString stringWithFormat:@"%i", kotuc]]; // 
    //write to file 
    [dict writeToFile:path atomically:YES]; 


    [dw release]; 
    [dict release]; 
    [subDict release]; 
    [keys release]; 
    [objects release]; 
} 
+0

問題是即使我能夠運行這條線沒有太大的問題,但是當我檢查我的data.plist時,它沒有任何值。 –

+0

TotalCategory是否滿足數據?關於你的代碼的奇怪之處在於,你想要在循環中選擇數據,但是你設置了一個靜態鍵(category或allCategory),任何字典中的鍵都假定是唯一的。這樣你可以只按每個字典記錄,所以不需要循環。 – Vanya

+0

yeah totalCategory中有7個不同的類別,我想將其中的7個存儲到pList中。有沒有關於pList的優秀解釋的教程?他們大多數只是有代碼如何發起路徑到你的plist,如documentDirectory和東西 –