使用字典中字典中的对象填充 mutableArray
我在从另一个 NSDictionary *dictionary(人员)内的一组 NSDictionaries(每个代表一个员工)填充对象数组(员工姓名)时遇到问题。每个子词典的键是员工 ID。
我很可能是从一个完全错误的方向来的,我是一个新手,但从我读到的内容来看应该是这样的,我已经设法从每个子词典中获取 pName(员工姓名) ,一切都转瞬即逝。我只是无法将 pName 添加到 MutableArray *names 中。
任何帮助或指导将不胜感激......
int i, count;
id key, value;
keys = [dictionary allKeys];
count = [keys count];
for (i = 0; i < count; i++)
{
key = [keys objectAtIndex: i];
value = [dictionary objectForKey: key];
NSLog (@"value:%@", value);
NSString *pName = [value objectForKey:@"personName"];
NSLog (@"pName:%@", pName);// the debugger shows the correct pName with each loop
[names addObject:pName];// this is wrong and i don't know why
}
NSLog (@"names:%@", names);// in the debugger names (null)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还可以使用 集合运算符,特别是
@unionOfObjects
运算符:请注意,
names
将归该方法所有(其保留计数为 1),但临时数组([personnel allValues]
和由valueForKeyPath:
创建的数组)会自动释放,并且不属于该方法。由于某种原因(可能是因为以“@”开头的键名在
valueForKey:
,因此valueForKeyPath:
不会相当于对valueForKey:
的调用序列),NSDictionary
没有valueForKeyPath:
方法,因此您首先需要将其转换为使用allValues
的数组。或者,您可以在类别中实现valueForKeyPath:
,也许从 GnuStep 或 cocotron 的(实际上并不支持@unionOfObjects
,但允许通过定义_kvo_operator_unionOfObjects:
方法轻松扩展)。You can also do this using collection operators, specifically the
@unionOfObjects
operator:Note that
names
will be owned by the method (its retain count is 1), but the interim arrays ([personnel allValues]
and the one created byvalueForKeyPath:
) are autoreleased and not owned by the method.For some reason (possibly because key names beginning with "@" are special in
valueForKey:
, and thusvalueForKeyPath:
wouldn't be equivalent to a sequence of calls tovalueForKey:
),NSDictionary
doesn't have avalueForKeyPath:
method, so you first need to convert it to an array usingallValues
. Alternatively, you could implementvalueForKeyPath:
in a category, perhaps starting from GnuStep's or cocotron's (which doesn't actually support@unionOfObjects
, but allows for easy extension by defining a_kvo_operator_unionOfObjects:
method).看起来您没有创建一个数组对象来放入您的名字。
在循环开始之前需要有这样的代码: ... 。这会创建一个空的可变数组。
It looks like you aren't creating an array object to put your names in. There needs to be code like this:
... before the start of the loop. That creates an empty mutable array.