如何通过iPhone应用程序在iphone的plist中保存数据

时间:2011-07-08 12:30:20

标签: iphone

  

可能重复:
  How to write data in plist?

嗨,我现在正在进行iphone编程。我想要添加数据并将其保存在plist ....-

我正在使用以下代码...

(void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"i amin did load");
    temp =[self readPlist:data];
    NSLog(@"dict data is %@",temp);
    [self writeToPlist];
    temp =[self readPlist:data];
    NSLog(@"dict data is %@",temp);

}
    //
//  NSError *error;
//  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
//  NSString *documentsDirectory = [paths objectAtIndex:0]; //2
//  NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; //3
//  
//  NSFileManager *fileManager = [NSFileManager defaultManager];
//  
//  if (![fileManager fileExistsAtPath: path]) //4
//  {
//      NSString *bundle = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]; //5
//      
//      [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
//  }
//  NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//  
//  NSLog(@"dictionary value is %@",savedStock);
//  
//  value = [[savedStock objectForKey:@"india"] intValue];
//  NSLog(@"value in plist is %d",value);
//  [savedStock release];

- (NSDictionary *)readPlist:(NSString *)fileName 
{  NSLog(@"i am in readlist method");
    NSLog(@"file paased is %@",fileName);
    //NSData *plistData;  
//  NSString *error;  
//  NSPropertyListFormat format;  
//  NSDictionary *plist;  

    NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];  
    NSMutableDictionary *plistDict=[[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    return plistDict;

}

- (void)writeToPlist
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

    [plistDict   setValue:@"karachi" forKey:@"pakistan"];
    [plistDict setObject:@"lahore" forKey:@"amerika"];
        [plistDict setObject:@"jabalpur" forKey:@"mp"];

    [plistDict writeToFile:filePath atomically: YES];

    /* This would change the firmware version in the plist to 1.1.1 by initing the NSDictionary with the plist, then changing the value of the string in the key "ProductVersion" to what you specified */
}

1 个答案:

答案 0 :(得分:0)

当您致电writeToFile:atomically时,您不需要提供完整路径,只需提供文件名。它会自动将其放在文档目录中。

基本上,在您编写变量filePath的任何地方,只需编写@"whatever.plist"