且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在属性列表的字典中向字典添加值

更新时间:2022-05-13 23:22:31

我相信您想执行以下操作:

I believe you want to do the following:

在.h中将您的cacheValue属性定义为可变字典.

Define your cacheValue property in the .h as a mutable dictionary.

NSMutableDictionary *cacheValue;

将plistXml序列化为NSMutableDictionary:

Serialize the plistXml as a NSMutableDictionary:

// This is the root Dictionary
NSMutableDictionary *temp = (NSMutableDictionary *)[NSPropertyListSerialization propertyListWithData:plistXML options:NSPropertyListMutableContainersAndLeaves format:NSPropertyListXMLFormat_v1_0 error:&error];

由于所有内容都是可变的,因此您现在可以读取,更新,插入,删除字典或其子内容的任何部分.例如,获取可变字典缓存值"就是:

Since everything is mutable, you can now read, update, insert, delete any part of the dictionary or its subcontents. For instance, grabbing the Mutable Dictionary "Cache Value" is just:

self.cacheValue = [temp objectForKey:@"Cache Value"];

请记住在没有键值的情况下检查对象是否为nil.密钥必须与出现在plist中的完全一样.

Remember to check that the object is not nil in case there isn't a value for the key. The key needs to be exactly as it appears in the plist.

在Mutable Dictionary中更新值很容易:

Updating a value in the Mutable Dictionary is easy:

[self.cache setValue:@"New Value" forKey:@"Sub"];

最后,要将更改保存在根可变字典的根目录中,回到plist:

And finally, to save the changes in the root Mutable Dictionary back to the plist:

/*
 The flag "atomically" specifies whether the file should be written atomically or not.
 If flag is YES, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path.
 If flag is NO, the dictionary is written directly to path.
 The YES option guarantees that path will not be corrupted even if the system crashes during writing.
 */
[self.temp writeToFile:plistPath atomically:YES];

希望这会有所帮助,加油!

Hope this helps, cheers!