drewish
drewish

Reputation: 9378

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?

Upvotes: 3

Views: 1445

Answers (3)

tdbit
tdbit

Reputation: 1003

Another way to approach this without the use of additional category method on NSNumber is to use the ternary operator and the NSNumber boolean literals:

self.item.completed = self.item.completed.boolValue ? @NO : @YES;

This should work with any recent version of Xcode but in particular it requires LLVM v4.0 or clang v3.1.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727087

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 )
-(NSNumber)negateBool;
@end

@implementation NSNumber ( NegateBoolean )
-(NSNumber)negateBool{
    return [NSNumber numberWithBool:![self boolValue]];
}
@end

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

Upvotes: 6

Tim
Tim

Reputation: 60150

You could consider setting up a "wrapper" getter and setter on self.item for a property, maybe called completedValue, that deals in BOOLs instead of NSNumbers. Might look a little like:

- (BOOL)completedValue {
    return [self.completed boolValue];
}

- (void)setCompletedValue:(BOOL)value {
    self.completed = [NSNumber numberWithBool:value];
}

Then your call just becomes:

self.item.completedValue = !self.item.completedValue;

Upvotes: 4

Related Questions