如何更新PLIST中的字符串

时间:2013-04-02 12:50:28

标签: iphone ios4

我有40项的数组,在dict.Dict里面包含2个字符串项,我想在用户点击uibutton时将字符串项写入0到1

<array>
    <dict>
        <key>quote</key>
        <string>Some Quotes</string>
        <key>favorite</key>
        <string>0</string>
    </dict>

</array>

我正在应用以下代码,但它对我不起作用......

-(void) addFavorite
{
    NSLog(@"Hello");

    [someButton setImage:[UIImage imageNamed:@"add_favoritegold.png"] forState:UIControlStateHighlighted];
    NSURL *documents = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *plistUrl = [documents URLByAppendingPathComponent:@"quotes.plist"];
    NSArray *plistContents = [NSArray arrayWithContentsOfURL:plistUrl];
    NSMutableDictionary *editFavorite = [plistContents objectAtIndex:1];
}

它不会将收藏夹0更改为1并且我的plist在支持文件中我是否必须在属性列表中进行任何更改。

4 个答案:

答案 0 :(得分:1)

-(void)btnClicked
{
    [arr_Data addObject:str1];
    [arr_Data addObject:str2];

    // get paths from root direcory
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);

   // get documents path
   NSString *documentsDirectory = [paths objectAtIndex:0];

   // get the path to our Data/plist file
   NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Data.plist"];

   // This writes the array to a plist file. If this file does not already exist, it creates a new one.
   [arr_Data writeToFile:path atomically: TRUE];
}

答案 1 :(得分:1)

请参考以下代码了解您的概念

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
      NSString  *plistdocumentsDirectory = [paths objectAtIndex:0]; 
    NsString * plistFilePath = [plistdocumentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"filename.plist"]];
  NSMutableArray  *savedStock = [[NSMutableArray alloc] initWithContentsOfFile:plistFilePath];
     [[savedStock objectAtIndex:indexForWheretoStoreData] setObject:@"your value" forKey:@"your key"];
  [savedStock writeToFile:filePath  atomically:YES];

答案 2 :(得分:0)

这是一个简单的4步流程:

1)选择词典(您想要更新“收藏夹”标签)。

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

2)设置新值。

[yourDict setValue:@"1" forKey:@"favorite"];

3)将其插入数组。

NSMutableArray *yourArray = [[NSMutableArray alloc] init];
[yourArray addObject:yourDict];

4)将该数组写入 yourPath

[yourArray writeToURL:yourPath atomically:YES];

答案 3 :(得分:0)

使用[yourArray writeToURL:yourPath atomically:YES];存储数据