drewish drewish - 5 months ago 43
Objective-C Question

Negate a Boolean stored in an NSNumber

I've got a managed object with an NSNumber that's just a Boolean value. When the user clicks a button I want to toggle that.

self.item.completed = [NSNumber numberWithBool:![self.item.completed boolValue]];

Is there a cleaner (or perhaps just more compact) way that I'm missing?


There is little you can do to the process of producing the negated value, but you can make the syntax of invoking it look less bulky by hiding your code in a category:

@interface NSNumber ( NegateBoolean )

@implementation NSNumber ( NegateBoolean )
    return [NSNumber numberWithBool:![self boolValue]];

Now you can use the new method like this:

self.item.completed = [self.item.completed negateBool];

You could also set up an NSArray with inversions, and use it as follows:

NSArray *inversions = [NSArray arrayWithObjects:[NSNumber numberWithBool:YES], [NSNumber numberWithBool:NO], nil];
self.item.completed = [inversions objectAtIndex:[self.item.completed boolValue]];