簡単なKVOの例 質問する

簡単なKVOの例 質問する

簡単な KVO の例を実行しようとしていますが、問題が発生しています。

これは私の *.m ファイルです:

#import "KVO_ViewController.h"

@interface KVO_ViewController ()

@property NSUInteger number;

@end

@implementation KVO_ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self addObserver:self forKeyPath:@"number" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)incNumber:(id)sender
{
    _number++;
    NSLog(@"%d", _number);
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"From KVO");

    if([keyPath isEqualToString:@"number"])
    {
        id oldC = [change objectForKey:NSKeyValueChangeOldKey];
        id newC = [change objectForKey:NSKeyValueChangeNewKey];

        NSLog(@"%@ %@", oldC, newC);
    }
}

@end

注記:クリックするとプロパティが増加するボタンがありますnumber。プロパティが変更された
ときに通知を受け取りたいですnumber

コードが機能しませんが、その理由がわかりません。

ベストアンサー1

KVOはセッターとゲッターで動作し、incNumberiVarに直接アクセスするので、代わりにself.number

- (IBAction)incNumber:(id)sender
{
    self.number++;
    NSLog(@"%d", self.number);
}

おすすめ記事