如何添加 NSArray 作为 NSMutableDictionary 键?
我尝试执行以下操作:
NSMutableArray *myArr = [NSMutableArray arrayWithArray:[myDict objectForKey:@"myKey"]];
[myArr addObject:@"New string xxx"];
[myDict setObject:myArr forKey:@"myKey"];
// Write to file (done successfully)
如您所见,我得到一个数组,该数组存储在 plist 中,键为 @"myKey"
,向其中添加一些对象并希望将其重新记录在plist,当然还有一些额外的值。
问题是,我的 plist 上发生以下情况:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs$
<plist version="1.0">
<dict>
<key>myKey</key>
<array>
<string>First entry on the plist</string>
<array>
<string>First entry on the plist</string>
<string>New string xxx</string>
</array>
</array>
</dict>
</plist>
当然,所需的输出是:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs$
<plist version="1.0">
<dict>
<key>myKey</key>
<array>
<string>First entry on the plist</string>
<string>New string xxx</string>
</array>
</dict>
</plist>
I tried doing the following:
NSMutableArray *myArr = [NSMutableArray arrayWithArray:[myDict objectForKey:@"myKey"]];
[myArr addObject:@"New string xxx"];
[myDict setObject:myArr forKey:@"myKey"];
// Write to file (done successfully)
As you can see, I get an array which is stored on a plist with the key @"myKey"
, add some objects to it and want to re-record it on the plist, with some extra values of course.
Problem is, the following happens on my plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs$
<plist version="1.0">
<dict>
<key>myKey</key>
<array>
<string>First entry on the plist</string>
<array>
<string>First entry on the plist</string>
<string>New string xxx</string>
</array>
</array>
</dict>
</plist>
The desired output is, of course:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs$
<plist version="1.0">
<dict>
<key>myKey</key>
<array>
<string>First entry on the plist</string>
<string>New string xxx</string>
</array>
</dict>
</plist>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过在再次设置之前调用
[myDict removeObjectForKey:@"myKey"]
?Have you tried calling
[myDict removeObjectForKey:@"myKey"]
before setting it again?其工作正常
输出:
its working fine
Output: