开发者

NSDictionary initialization results in "EXC_BAD_ACCESS"

开发者 https://www.devze.com 2023-03-14 15:03 出处:网络
I can not figure out why this code is bad. I thought it was ok to use static strings in dictionaryWithObjectsAndKeys however it fails at runtime with a EXC_BAD_ACCESS. I used the debugger to identify

I can not figure out why this code is bad. I thought it was ok to use static strings in dictionaryWithObjectsAndKeys however it fails at runtime with a EXC_BAD_ACCESS. I used the debugger to identify that it is in fact failing at the definition line. It never outputs "Made it here".

- (NSString *)polyName:(NSUInteger)ver开发者_运维技巧tices { 
    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
} 


The problem is here:

@"pentagon","5"

It expects an object (NSString) but instead there's a regular string.
Change it to:

@"pentagon", @"5"


What line does the EXC_BAD_ACCESS occur on? Utilize breakpoints and let us know.

For now, if I were you, I'd do something like this:

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];

instead of how you have it now.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号