Reputation: 9378
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
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
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
Reputation: 60150
You could consider setting up a "wrapper" getter and setter on self.item
for a property, maybe called completedValue
, that deals in BOOL
s 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