无法从 NSDictionary 访问密钥
我有以下代码:
- (id)initWithDictionaryRepresentation:(NSDictionary *)dictionary {
self = [super init];
if (self != nil) {
dictionaryRepresentation = [dictionary retain];
NSArray *allKeys = [dictionaryRepresentation allKeys];
NSDictionary *k = [dictionaryRepresentation objectForKey:[allKeys objectAtIndex:[allKeys count] - 1]];
NSArray *stepDics = [k objectForKey:@"Steps"];
numerOfSteps = [stepDics count];
steps = [[NSMutableArray alloc] initWithCapacity:numerOfSteps];
for (NSDictionary *stepDic in stepDics) {
[(NSMutableArray *)steps addObject:[UICGStep stepWithDictionaryRepresentation:stepDic]];
}
............
}
我的应用程序在这一行崩溃:
NSArray *stepDics = [k objectForKey:@"Steps"];
但如果我尝试这样做也会崩溃: NSArray *stepDics = [k objectForKey:@"pr"];
。看来我不能访问任意键!
这就是我的字典的样子: http://pastebin.com/w5HSLvvT
有什么想法吗?
I have the following code:
- (id)initWithDictionaryRepresentation:(NSDictionary *)dictionary {
self = [super init];
if (self != nil) {
dictionaryRepresentation = [dictionary retain];
NSArray *allKeys = [dictionaryRepresentation allKeys];
NSDictionary *k = [dictionaryRepresentation objectForKey:[allKeys objectAtIndex:[allKeys count] - 1]];
NSArray *stepDics = [k objectForKey:@"Steps"];
numerOfSteps = [stepDics count];
steps = [[NSMutableArray alloc] initWithCapacity:numerOfSteps];
for (NSDictionary *stepDic in stepDics) {
[(NSMutableArray *)steps addObject:[UICGStep stepWithDictionaryRepresentation:stepDic]];
}
............
}
My app crashes at this line:
NSArray *stepDics = [k objectForKey:@"Steps"];
but also crashes if I try this : NSArray *stepDics = [k objectForKey:@"pr"];
.It seems that I can't acces any of the keys!
This is how my dictionary looks like:
http://pastebin.com/w5HSLvvT
Any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSArray *allKeys = [dictionaryRepresentation allKeys];
将以不可预测的顺序返回键,因此您不应该使用它,
因为它每次都可能返回不同的内容,这在 for 的文档中显示NSDictionary 文档。
为什么不尝试
NSArray *allKeys = [dictionaryRepresentation allKeys];
Will return you the keys in an unpredictable order, so you shouldn't be using
as it could return something different every time, this is shown in the documentation for for this function in the NSDictionary Documentation.
Why dont you try
如果您请求不存在的键,字典将返回
nil
。它崩溃的事实意味着您有内存管理错误,不是在上面显示的代码中,而是在创建传递到initWithDictionaryRepresentation:
方法中的字典的代码中。您过度释放了存储在字典的@"Steps"
键中的数组。A dictionary will return
nil
if you ask for a key that doesn't exist. The fact that it's crashing means that you have a memory management error, not in the code you show above but in the code that creates the dictionary that is passed into yourinitWithDictionaryRepresentation:
method. You're over-releasing the array that's stored in the@"Steps"
key of the dictionary.