2010-06-25 76 views
2

如何遞增整數屬性?遞增屬性int(self.int ++)

你不能做self.integer++,你可以做integer++,但我不知道用是否會保留它..

將最後一個保留「整數」的價值?

謝謝。

回答

3

integer++適用,因爲您直接訪問integer並將新值指定給integer而不是發送消息和使用訪問器。假設integer被聲明爲NSInteger屬性,以下語句將對整數值具有相同的效果,但直接訪問不符合KVO。

[self setInteger:0]; 
self.integer = self.integer + 1; // use generated accessors 
NSLog(@"Integer is :%d",[self integer]); // Integer is: 1 
integer++; 
NSLog(@"Integer is :%d",[self integer]); // Integer is: 2 
+1

好的,謝謝:) [blahblahblah,試圖填補這個評論,愚蠢的字符限制。] – Emil 2010-06-25 14:09:04

0

我相信Obj-C在過去的一兩年裏已經更新,所以這種代碼的工作原理。我寫了一個快速測試,發現下面的代碼就是所有有效和工作原理:

#import <Cocoa/Cocoa.h> 

@interface TheAppDelegate : NSObject <NSApplicationDelegate> { 
    NSUInteger value; 
} 

@property NSUInteger otherValue; 

- (NSUInteger) value; 
- (void) setValue:(NSUInteger)value; 

@end 

在我的.m:

#import "TheAppDelegate.h" 

@implementation TheAppDelegate 

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    value = self.otherValue = 1; 
    NSLog(@"%lu %lu", (unsigned long)value, (unsigned long)self.value); 
    NSLog(@"%lu %lu", (unsigned long)_otherValue, (unsigned long)self.otherValue); 
    self.value++; 
    self.otherValue++; 
    NSLog(@"%lu %lu", (unsigned long)value, (unsigned long)self.value); 
    NSLog(@"%lu %lu", (unsigned long)_otherValue, (unsigned long)self.otherValue); 
} 

- (NSUInteger) value 
{ 
    return value; 
} 

- (void) setValue:(NSUInteger)_value 
{ 
    value = _value; 
} 

@end 

我的輸出:

在我的.h

1 1 
1 1 
2 2 
2 2 

我相信這裏有一個技術文檔,我讀了這個解釋,但我不記得我在哪裏找到它。我相信它說的線沿線的東西:

x++將得到改變,以x+=1

x+=yx=x+y

而且所取代,x=y.a=z將被替換爲y.a=z,x=y.a(因爲當你處理屬性 - 不是結構)