简体   繁体   中英

iOS:Read and Write into Plist

I want to save the token from from the server into a plist. I am not sure If I have to create a plist firs or it can automatically get created with the following code in my Document directroy. However, I am not able to create a plist and write my dictionary into it. Here is my code

-(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?


}   

why don't you save it using NSUserDefaults?

here's an example code :

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];  

don't forget to synchronize in the final.

and when you need the data you need to call standartUserDefaults 's :valueForKey method.

hope this helps..

I found a way to easily create a plist file programatically, this works for me:

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];
}

Change what is inside the if statement and it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM