2011-07-25 49 views
0

當我的應用程序啓動時,看看是否存在plist,如果它不創建它。writeToFile:原子只會第一次工作

NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"history.plist"]; 
    success = [fileManager fileExistsAtPath:filePath]; 
    if (success) { 
     NSArray *arr = [[NSArray alloc] initWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:@"history.plist"]]; 
     for (NSDictionary *par in arr) { 
      [self.history addObject:[[Paradero alloc] initWithDictionary:par]]; 
     } 
    } else { 
     [fileManager createFileAtPath:filePath contents:nil attributes:nil]; 
    } 

現在,當用戶關閉應用程序,以提供持久性我的數據保存到該文件

- (void)applicationDidEnterBackground:(UIApplication *)application { 
    /* 
    Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    If your application supports background execution, called instead of applicationWillTerminate: when the user quits. 
    */ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"history.plist"]; 
    NSLog(@"%@", filePath); 
    NSMutableArray *temparray = [[NSMutableArray alloc] initWithCapacity:5]; 
    for (Paradero *parada in self.history) { 
     [temparray addObject:[parada asDictionary]]; 
    } 
    NSLog(@"%@", temparray); 
    NSLog(@"%c",[temparray writeToFile:filePath atomically:NO]); 

    NSLog(@"yei"); 
} 

對象被轉換爲一個字典用的NSString,NSArrays所以它可以被保存到文件。這是第一次發生,這意味着文件已經創建,沒有任何內容,它工作得很好,但是當保存新數據的時候,它失敗了,沒有理由給出。

+0

你似乎在兩個addObject調用上都在泄漏內存,就像在旁邊一樣。我不確定爲什麼你明確地創建history.plist作爲一個空文件?在你的日誌中,我相信它顯示臨時數組不是空的? – onnoweb

+0

@onnoweb,我不是空的。 –

+0

所有我能想到的是確保[parada asDictionary]確實返回一個字典,其對象都是屬性列表對象。 – onnoweb

回答

4

已解決。 備案: 第一個問題是,我在iOS5模擬器上測試,好吧,我不知道如何修復它。

真正的問題是因爲有一些NSNull,所以我只需要將它們變成空字符串。

記住要檢查NSNulls,如果它們從Web服務中轉出來,它們真的很痛苦。