nukerebel
nukerebel

Reputation: 119

Incrementing an NSNumber

New to obj-C and Cocoa here

I'm trying to just increment a variable in a method and, being used to C++, I want to just use the terminology of variable++, but that doesn't work on an NSNumber, so I've come up with

player1Points = [NSNumber numberWithInt: ([ player1Points intValue ] + 1) ];

I am tempted to just redeclare player1Points as an int in the header, but I want to keep @synthesize and @property so that I don't have to write get and set routines.

Is there an easier way to write this line of code?

Upvotes: 0

Views: 2991

Answers (3)

Kaan Dedeoglu
Kaan Dedeoglu

Reputation: 14841

Agree with all the answers, one other option (although perhaps over coding), is to create a category on NSNumber with an instance method called increase (or something else). So you can have something like [player1Points increase]; anywhere in your app.

Upvotes: 0

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21966

You can still declare it NSInteger, a property may be a primitive type as well:

@property (nonatomic,assign) NSInteger player1Points;

You can still synthesize it.

Alternatively, there is a new syntax which will make the use of NSNumber more comfortable:

player1Points = @(player1Points.integerValue+1);

Upvotes: 7

Ned
Ned

Reputation: 6270

You can use primitives as properties, like so:

@property (nonatomic, assign) int player1Points;

Upvotes: 1

Related Questions