0

plistの値を変更しようとしています(開始値が0の@key "userId")

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GlobalSettings" ofType:@"plist"];
NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
NSDictionary *userId = [data objectForKey:@"userId"];

[data setValue:(@"99") forKey:@"userId"];
[data writeToFile:plistPath atomically: NO];

userId = [data objectForKey:@"userId"];
NSLog(@"%@", userId); 

ログには、値が99に変更されたことが示されていますが、plistを開くと、値はまだ0です。

4

1 に答える 1

4

アプリケーションのメインバンドルにデータを保存することはできません。代わりに、次のようにドキュメントディレクトリに保存する必要があります。

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

if([[NSFileManager defaultManager] fileExistsAtPAth:plistFilePath]) 
{//already exits

   NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistFilePath];
   NSDictionary *userId = [data objectForKey:@"userId"];
   [data setValue:(@"99") forKey:@"userId"]; //new value here
   [data writeToFile:plistPath atomically: YES];
   userId = [data objectForKey:@"userId"];
   NSLog(@"%@", userId); 
}
else{ //firstly take content from plist and then write file document directory 

 NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GlobalSettings" ofType:@"plist"];
 NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
 NSDictionary *userId = [data objectForKey:@"userId"];

 [data setValue:(@"99") forKey:@"userId"];//new value here
 [data writeToFile:plistFilePath atomically:YES];

 userId = [data objectForKey:@"userId"];
 NSLog(@"%@", userId); 
}
于 2012-09-11T08:45:43.000 に答える