2011-10-10 30 views
0
存取權限關鍵

我有以下代碼:不能從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

任何想法?

回答

1

NSArray *allKeys = [dictionaryRepresentation allKeys];

將返回鍵在一個不可預知的順序,所以你不應該使用

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

,因爲它可能返回每次不同的東西,這是在文檔中所示這個功能在NSDictionary Documentation

元素的數組中的順序沒有定義

你爲什麼不嘗試

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

字典將返回nil如果你問的是不存在的關鍵。它崩潰的事實意味着你有一個內存管理錯誤,而不是你在上面顯示的代碼中,而是在創建傳遞到initWithDictionaryRepresentation:方法中的字典的代碼中。您過度釋放存儲在字典的@"Steps"鍵中的數組。