我无法弄清楚为什么这段代码很糟糕。我认为在dictionaryWithObjectsAndKeys中使用静态字符串是可以的,但它在运行时因EXC_BAD_ACCESS而失败。我使用调试器来识别它在定义行中实际上是失败的。它永远不会输出“Made it here”。
- (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
}
答案 0 :(得分:18)
问题在于:
@"pentagon","5"
它需要一个对象(NSString),而是有一个常规字符串 将其更改为:
@"pentagon", @"5"
答案 1 :(得分:-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];
而不是现在的方式。