0

我有一个字典数组,它保存在应用程序的文档目录中如何更新特定键和索引的值?例如:我想更新第二个字典人的名字

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
      <dict>
            <key>personName</key>
            <string>John Sculey</string>
            <key>isPersonAdult</key>
            <true/>
            <key>personID</key>
            <integer>12541</integer>
            <key>personPicture</key>
            <string>john.jpg</string>
            <key>personDesignation</key>
            <string>Branding Manager</string>
            <key>personDepartment</key>
            <integer>2</integer>
            <key>personEmail</key>
            <string>john@johnsculey.com</string>
    </dict>
    <dict>
           <key>personName</key>
            <string>Chris Seattle</string>
            <key>isPersonAdult</key>
            <true/>
            <key>personID</key>
            <integer>89854</integer>
            <key>personPicture</key>
            <string>chris.jpg</string>
            <key>personDesignation</key>
            <string>Branding Manager</string>
            <key>personDepartment</key>
            <integer>2</integer>
            <key>personEmail</key>
            <string>chris@johnsculey.com</string>
    </dict>

等等....

4

4 回答 4

1

所以,假设你的字典是可变的,

[[array objectAtIndex:1] setObject:@"New Name" forKey:@"personName"];

(如果不是,请事先创建它的可变副本。)

于 2013-01-01T22:52:03.097 回答
0

我的 2 美分也是 :D

id data = [NSData dataWithContentsOfFile:plistFile];
NSArray *plist = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainersAndLeaves format:nil error:nil];
assert([plist isKindOfClass:[NSArray class]]);

//every element in the array is mutable
NSMutableDictionary *dict = plist[1];
dict[@"key"] = @"value";
于 2013-01-01T23:03:49.007 回答
0

不确定,如果我得到你的问题是正确的。但是,如果您要问,如何在数组的特定索引处访问字典,这将是方式:

NSMutableDictionary *person = [NSMutableDictionary dictionaryWithDictionary:[array objectAtIndex:1]];
[person setValue:@"Chris Washington" forKey:@"personName"];

数组持有什么样的对象并不重要;它可以是数字或 - 在你的情况下 - 字典对象。您可以正常访问它们。

于 2013-01-01T22:42:30.730 回答
-1

你可以用几行代码做你想做的事……首先你从数组中得到你想要编辑的字典,然后你改变你的键的值。我还没有测试过这段代码,但它应该可以正常工作!

NSURL *documents = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *plistUrl = [documents URLByAppendingPathComponent:@"yourPlistName.plist"];
NSArray *plistContents = [NSArray arrayWithContentsOfURL:plistUrl];
NSMutableDictionary *personToEdit = [plistContents objectAtIndex:1];
[personToEdit setValue:@"value you want to set" forKey:@"your key"];
于 2013-01-01T22:57:10.057 回答