开发者

NSNumber + a real number (e.g 50) = not possible?

开发者 https://www.devze.com 2023-01-05 02:49 出处:网络
i have an NSNumber that is taken from a string like this NSNumberFormatter *f = [[NSNumberFormatter alloc]init];

i have an NSNumber that is taken from a string like this

NSNumberFormatter *f = [[NSNumberFormatter alloc]init];
[f setNumberStyle:NS开发者_运维问答NumberFormatterDecimalStyle];

BRNumber = [f numberFromString:BRString];

of course this returns a value but now i wish to do something like

id y = BRNumber + 50; 

It seems that this is not possible. So how should i go about doing this.?


You need to get the raw integer before doing the computation, and wrap it back to an NSNumber afterwards.

NSNumber* y = [NSNumber numberWithInt:[BRNumber intValue] + 50];

If you're doing this a lot, you could create a category:

@implementation NSNumber (Arithmetics)
-(NSNumber*)numberByAddingInt:(int)val {
   return [NSNumber numberWithInt:[self intValue] + val];
}
@end

then you could use

NSNumber* y = [BRNumber numberByAddingInt:50];

There's no shorter ways, since ObjC doesn't have operator overloading.

0

精彩评论

暂无评论...
验证码 换一张
取 消