Cbas
Cbas

Reputation: 6213

Setting and getting BOOL values in NSDictionary

I need a dictionary of Strings that point to boolean values.

I have an NSDictionary toolStates that I create like this

NSArray *keys = [NSArray arrayWithObjects:@"X", @"Y", nil];
NSArray *isActive = [NSArray arrayWithObjects:[NSNumber numberWithBool:NO], [NSNumber numberWithBool:YES], nil];
toolStates = [NSDictionary dictionaryWithObjects:isActive forKeys:keys];

elsewhere in my class, I am trying to retrieve and compare the booean value like this

if ([toolStates valueForKey: @"X"] == [NSNumber numberWithBool:NO]) NSLog(@"%s", "X = NO");

I know that both portions of code are running, but I get a "EXC_BAD_ACCESS" error on the if statement with the output:

<Error>: CGAffineTransformInvert: singular matrix.

Is there something wrong with the comparison?

I get the same error when I try this:

[toolStates setValue:[NSNumber numberWithBool:YES] forKey:@"X"];

Upvotes: 1

Views: 10384

Answers (1)

Conrad Shultz
Conrad Shultz

Reputation: 8808

There are a couple problems with what you have written, but neither of them I think are responsible for your immediate issue (see below). Let's go through a few of the issues.

  1. Your [toolStates setValue:forKey:] can't work as written because you have an NSDictionary, not NSMutableDictionary.
  2. -valueForKey: returns id (i.e. it's going to return your NSNumber instance, not a BOOL. As such, your comparison is incorrect. Your == is doing pointer comparison, which is not what you want. (It might work here if NSNumber is optimized to return a singleton from +numberWithBool: but that's not behavior you should count on.) The correct way to do equality comparison in Objective-C is the -isEqual: method, e.g., if ([[toolStates valueForKey:@"X"] isEqual:[NSNumber numberWithBool:NO]).

But you are getting EXC_BAD_ACCESS which normally means you are accessing a deallocated object. My suspicion is bolstered by the fact that you are getting an error related to Core Graphics, which has nothing to do with your code (suggesting your garbage pointer is now pointing to something graphics related).

Are you using ARC? If not, I don't see you retaining toolStates anywhere. If you aren't, and you are accessing it after the next turn of the run loop (which it sounds like), then you would expect a crash. If this doesn't sound right, or you can't find the problem, try the following:

  1. Run your code through the Xcode static analyzer (Clang). Fix any warnings it throws at you.
  2. Run your code with zombies enabled, and watch for a "message sent to deallocated instance" or something to that effect.

Upvotes: 12

Related Questions