无法从 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

任何想法?

NSArray *allKeys = [dictionaryRepresentation allKeys];

将以不可预测的顺序返回键,因此您不应该使用

id key = [allKeys objectAtIndex:[allKeys count] - 1]

,因为它每次都可能返回不同的东西,这在NSDictionary文档中的这个函数的文档中有显示。

数组中元素的顺序没有定义

你为什么不试试

NSDictionary* a = [dictionary objectForKey:@"A"];
NSArray* stepDics = [a objectForKey:@"Steps"];

如果您请求一个不存在的键,字典将返回nil。它崩溃的事实意味着您有一个内存管理错误,不是在上面显示的代码中,而是在创建传递到initWithDictionaryRepresentation:方法的字典的代码中。您过度释放了存储在字典的@"Steps"键中的数组

最新更新