在 NSDictionary 中操作数组
我尝试直接操作 NSMutableDictionary
中的数组:
[[myDictionary objectForKey: @"key"] addObject: object];
这不起作用!我什至尝试过类型转换:
[(NSMutableArray*)[myDictionary objectForKey: @"key"] addObject: object];
这也不起作用!
唯一有效的方法是:
NSMutableArray *array = [myDictionary objectForKey: @"key"];
[array addObject: object];
[myDictionary setObject: array forKey: @"key"]
有没有一种方法可以像第一个代码片段一样操作字典中的数组?即无需创建新数组、操作它然后保存它?
I tried to manipulate an array in an NSMutableDictionary
directly:
[[myDictionary objectForKey: @"key"] addObject: object];
This doesn't work! I even tried type casting:
[(NSMutableArray*)[myDictionary objectForKey: @"key"] addObject: object];
This didn't work either!
The only way that worked was:
NSMutableArray *array = [myDictionary objectForKey: @"key"];
[array addObject: object];
[myDictionary setObject: array forKey: @"key"]
Is there a way to manipulate the array in the dictionary similar to the first code snippet; i.e. without having to create a new array, manipulating it and then saving it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否有机会从文件或 URL 加载 NSDictionary ?来自 API 文档:“即使字典是可变的,该字典包含的对象也是不可变的。”
Are you loading the NSDictionary from a file or URL by any chance? From the API docs: "The objects contained by this dictionary are immutable, even if the dictionary is mutable."
问题是我没有在 NSMutable 字典中分配数组,即在添加对象之前使用以下代码:
The problem was that I wasn't allocation the array within the NSMutable Dictionary i.e. before adding objects use the following code: