Reputation: 89
Can anyone tell me the most efficient way to make a negative NSNumber positive?
Upvotes: 1
Views: 3370
Reputation: 727087
Doing this generically is surprisingly complex, because you need to find out the proper type of the number inside NSNumber
.
Here is one way of doing it: add a category, and use a switch
statement in the implementation to dispatch on the value of objCType
@interface NSNumber (AbsoluteValue)
-(NSNumber*)abs;
@end
@implementation NSNumber (AbsoluteValue)
-(NSNumber*)abs {
switch (self.objCType[0]) {
// Cases below cover only signed types
case 'c': return [NSNumber numberWithChar:abs([self charValue])];
case 's': return [NSNumber numberWithShort:abs([self shortValue])];
case 'i': return [NSNumber numberWithInt:abs([self intValue])];
case 'q': return [NSNumber numberWithLongLong:llabs([self longLongValue])];
case 'f': return [NSNumber numberWithFloat:fabsf([self floatValue])];
case 'd': return [NSNumber numberWithDouble:fabs([self doubleValue])];
// Otherwise, the number is of an unsigned type, so it can be returned directly
default: return self;
}
}
@end
You can optimize this by returning self
when the number is positive.
Upvotes: 3
Reputation: 2617
Get the absolute value like that:
number = [NSNumber numberWithDouble:fabs([number doubleValue])];
Upvotes: 2