2011-07-25 7 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を空のファイルとして作成するのか分かりません。あなたのログには、temp配列が空でないことが示されています。 – onnoweb

+0

@onnoweb、私は空ではありません。 –

+0

私が考えることができるのは、[parada asDictionary]が本当にオブジェクトがすべてのプロパティリストオブジェクトである辞書を返すことを確認することだけです。 – onnoweb

答えて

4

解決済み。 レコードについて: 最初の問題は、iOS5 Simulatorでテストしていたことです。まあ、私はまだそれを修正する方法がわかりません。

実際の問題は、NSNullがいくつかあったためです。そのため、空の文字列にする必要がありました。

NSNullを確認することを忘れないでください.SNNullがWebサービスから出てくると、本当に痛いです。

関連する問題