can't acces key from NSDictionary
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 = [s开发者_运维百科tepDics 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?
NSArray *allKeys = [dictionaryRepresentation allKeys];
Will return you the keys in an unpredictable order, so you shouldn't be using
id key = [allKeys objectAtIndex:[allKeys count] - 1]
as it could return something different every time, this is shown in the documentation for for this function in the NSDictionary Documentation.
The order of the elements in the array is not defined
Why dont you try
NSDictionary* a = [dictionary objectForKey:@"A"];
NSArray* stepDics = [a objectForKey:@"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 your initWithDictionaryRepresentation:
method. You're over-releasing the array that's stored in the @"Steps"
key of the dictionary.
精彩评论