2011-11-11 8 views
0

私はplistにデータを読み書きするクラスに問題があります。ここにいくつかのコードがあります:Plist Read and Write iPhone

この最初のチャンクは私のすべてのplistの読み書きメソッドを持つ私のカスタムクラスからです。

私はその後、別のクラス希望輸入でクラスメソッドを作成して使用
-(NSString *) dataFilePath{ 
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentDirectory = [path objectAtIndex:0]; 
    return [documentDirectory stringByAppendingPathComponent:@"userInformation.plist"]; 
} 

-(bool)readUserIsMale{ 
    NSString *filePath = [self dataFilePath]; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {   
     NSDictionary *boolDict = [[NSDictionary alloc] initWithContentsOfFile:[self dataFilePath]]; 
     return [[boolDict objectForKey:@"boolUserIsMale"] boolValue]; 
    } 
    return nil; 
} 

-(void)writeUserIsMale:(bool)boolValue{ 
    NSDictionary *boolDict = [[NSDictionary alloc] init]; 
    [boolDict setValue:[NSNumber numberWithBool:boolValue] forKey:@"boolUserIsMale"]; 
    [boolDict writeToFile:[self dataFilePath] atomically:YES]; 
} 

#import "plistReadWrite.h" 
plistReadWrite *readWrite; 

私がしようとすると、コンソールにその値が表示されている場合、私は(ヌル)のリターンを得ます。私はそうのようないくつかのデータを書いた後

NSLog(@"%@",[readWrite readUserIsMale]); 

これはもちろんです:

[readWrite writeUserIsMale:isUserMale]; 

isUserMaleがブール値です。

これ以上の情報が必要な場合は、何か助けていただければ幸いです。ありがとう。

答えて

0

これはほぼ正しいと思います。あなたのwriteUserIsMaleで:方法あなたが実際にそのキー(あるとして、これはあなたのためにクラッシュしているはずなので、私はコピー/ペーストの問題を推測している?)

//NSDictionary *boolDict = [[NSDictionary alloc] init]; 
//should be: 

NSMutableDictionary *boolDict = [[NSMutableDictionary alloc] init]; 

そしてときに設定できますので、あなたが、可変辞書をしたいですあなたは値を記録し、そのブール値(またはBOOL)を覚えているプリミティブではなく、オブジェクトには:

NSLog (@"%d",[readWrite readUserIsMale]); // Will print 0 or 1 
// or if you prefer: 
NSLog (@"%@", ([readWrite readUserIsMale]? @"YES":@"NO")); // print YES or NO 

最後に、これはObjective-Cのであるから、私はおそらくBOOLの代わりに、ブール値を使用します。

これは単なる例であり、この種のことについてNSUserDefaultsについて知っていると仮定しています。

希望に役立ちます。