代码之家  ›  专栏  ›  技术社区  ›  Emil

递增属性int(self.int++)

  •  2
  • Emil  · 技术社区  · 15 年前

    如何增加整数属性?

    你做不到 self.integer++ 你可以做到 integer++ 但我不确定这是否能保持下去。

    最后一个会保留“整数”的值吗?

    谢谢。

    2 回复  |  直到 11 年前
        1
  •  3
  •   falconcreek    15 年前

    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
    
        2
  •  0
  •   ArtOfWarfare    11 年前

    I believe Obj-C was updated in the last year or two so that this kind of code works. 我写了一个快速测试,发现以下代码都是有效的:

    我的H:

    #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
    

    我的输出:

    1 1
    1 1
    2 2
    2 2
    

    我相信在我读到的某个地方有一个技术文档解释了这一点,但我记不起在哪里找到了它。我相信它说的是:

    x++ 将改为 x+=1

    x+=y x=x+y

    x=y.a=z y.a=z,x=y.a