2011-06-22 53 views
4

我找不出爲什麼這個代碼是壞的。我認爲可以在dictionaryWithObjectsAndKeys中使用靜態字符串,但在運行時使用EXC_BAD_ACCESS失敗。我使用調試器來確定它實際上在定義線上失敗。它從來沒有輸出「在這裏製造」。NSDictionary初始化結果「EXC_BAD_ACCESS」

- (NSString *)polyName:(NSUInteger)vertices { 
    NSLog(@"looking for polyName with %d vertices.", vertices); 

    NSDictionary *polNameDict = [NSDictionary dictionaryWithObjectsAndKeys: 
          @"triangle", @"3", 
          @"square", @"4", 
          @"pentagon","5", 
          @"Hexagon", @"6", 
          @"Heptagon", @"7", 
          @"Octagon", @"8", 
          @"Nonagon", @"9", 
          @"Decagon", @"10", 
          @"Hendecagon", @"11", 
          @"Dodecagon", @"12", 
          nil]; 

    NSLog(@"Made it here"); 

    NSString *key = [NSString stringWithFormat: @"%d", vertices]; 
    NSString *polName = [polNameDict objectForKey:key]; 
    return (polName); 
    // Memory management: No need to release polNameDict, key, polName because they use 
    // convenience functions 
} 
+14

首先修復'@ 「五邊形」, 「5」''到@ 「五邊形」,@ 「5」'。 – Anna

+2

@安娜 - 應該作爲回答,因爲它似乎實際上是問題 –

+0

安娜我愛你。 OMG,我浪費了一個小時。 ARRRGGH。愚蠢的錯字。謝謝。這個社區以btw爲基礎。 – vesselhead

回答

18

的問題是在這裏:

@"pentagon","5" 

該公司預計的對象(NSString的),而是有一個正常的字符串。
將其更改爲:

@"pentagon", @"5" 
-4

EXC_BAD_ACCESS發生在哪一行?利用斷點並讓我們知道。

現在,如果我是你,我會做這樣的事情:

NSDictionary *polNameDict = [[NSDictionary alloc] initWithObjectsAndKeys: 
          @"triangle", @"3", 
          @"square", @"4", 
          @"pentagon",@"5", 
          @"Hexagon", @"6", 
          @"Heptagon", @"7", 
          @"Octagon", @"8", 
          @"Nonagon", @"9", 
          @"Decagon", @"10", 
          @"Hendecagon", @"11", 
          @"Dodecagon", @"12", 
          nil]; 

,而不是你現在怎樣擁有它。

+0

Tx。我確實使用調試器來發現它在initWithObjectsAndKeys行失敗。我會交換分配,看看會發生什麼。 – vesselhead

+0

然後稍後再發布它... – esqew

+0

爲什麼downvote ??? – esqew