我想将令牌从服务器保存到plist中。我不确定我是必须创建plist firs,还是可以在我的文档目录中使用以下代码自动创建它。但是,我不能创建plist并将我的字典写入其中。以下是我的代码
-(void)writeToPlist:(NSString*)value forkey:(NSString *)key
{
NSLog(@"Write plist here");
//NSError *error;
NSArray *paths=NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString* path=[documentDirectory stringByAppendingFormat:@"Util.plist"];
NSLog(@"The path is %@",path);
NSFileManager *fileManager=[NSFileManager defaultManager];
NSMutableDictionary *data;
if(![fileManager fileExistsAtPath:path])
{
path=[[NSBundle mainBundle]pathForResource:@"Util" ofType:@"plist"];
}
[data setObject:value forKey:key];
[data writeToFile:path atomically:YES];//will it create the plist?
} 发布于 2012-05-02 06:46:20
为什么不使用NSUserDefaults保存它呢?
下面是一个示例代码:
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if([standardUserDefaults objectForKey:@"your-key-goes-here"] == nil) //this means you don't have that key
{[standardUserDefaults setValue:@"your-value-goes-here" forKey:@"your-key-goes-here"];}
[standardUserDefaults synchronize]; 别忘了在决赛中保持同步。
当您需要数据时,您需要调用standartUserDefaults的:valueForKey方法。
希望这能帮上忙..
发布于 2012-05-02 07:16:27
我找到了一种通过编程轻松创建plist文件的方法,这对我很有效:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingString:@"/myFile.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
NSDictionary *emptyDic = [NSDictionary dictionary];
[emptyDic writeToFile:path atomically:YES];
}更改if语句中的内容,它就会起作用。
https://stackoverflow.com/questions/10405376
复制相似问题