2013-03-07 63 views
0

新建OBJ-C和Cocoa這裏遞增一個NSNumber

我想只是遞增的方法的變量,並使用C++的,我只想用變量++的術語,但沒有按沒有工作的NSNumber,所以我想出了

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

我很想只是重新聲明player1Points作爲頭一個int,但我想保持@synthesize和@property,這樣我就不用寫獲取和設置程序。

有沒有更簡單的方法來寫這段代碼?

+2

您可以使用帶'int'屬性的'@ synthesize'和'@ property'。 – 2013-03-07 23:23:11

+0

看看[NSNumber類參考](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html) – 2013-03-08 12:03:24

回答

7

你仍然可以把它聲明NSInteger的,屬性可以是原始類型,以及:

@property (nonatomic,assign) NSInteger player1Points; 

您仍然可以合成它。

另外,還有一個新的語法,這將使使用NSNumber的更舒適:

player1Points = @(player1Points.integerValue+1); 
+0

像冠軍一樣工作,謝謝 – nukerebel 2013-03-08 01:47:55

1

可以使用原語的屬性,就像這樣:

@property (nonatomic, assign) int player1Points; 
0

與所有的答案同意,另一種選擇(儘管可能是編碼過度),是使用稱爲增加(或其他)的實例方法在NSNumber上創建一個類別。所以你可以在你的應用程序的任何地方有類似[player1Points increase];的東西。