当价值发生变化时,KVO不会触发

时间:2012-09-13 14:45:32

标签: objective-c macos key-value-observing foundation key-value-coding

我正在尝试使用Apple的KVC进行一些测试,但出于某种原因,当我通过KVC更改值时,我无法触发KVO。

我有以下代码:

#import <Foundation/Foundation.h>

@interface Character : NSObject
{
    NSString *characterName;
    NSInteger ownedClowCards;
}
@property (nonatomic, retain) NSString *characterName;
@property (nonatomic, assign) NSInteger ownedClowCards;
-(void)hasLostClowCard;
-(void)hasGainedClowCard;
@end

@implementation Character
@synthesize characterName;
@synthesize ownedClowCards;

-(void)hasLostClowCard
{

}

-(void)hasGainedClowCard
{

}

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

@end

int main()
{
    Character *sakura;
    Character *shaoran;

    //---------------------------------------------------------------------
    // Here begins the KVO section.

    [sakura addObserver:sakura forKeyPath:@"ownedClowCards" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

    //Create and give the properties some values with KVC...

    sakura = [[Character alloc] init];
    [sakura setValue:@"Sakura Kinomoto" forKey:@"characterName"];
    [sakura setValue:[NSNumber numberWithInt:20] forKey:@"ownedClowCards"];

    shaoran = [[Character alloc] init];
    [shaoran setValue:@"Li Shaoran" forKey:@"characterName"];
    [shaoran setValue:[NSNumber numberWithInt:21] forKey:@"ownedClowCards"];

    //Done! Now we are going to fetch the values using KVC.

    NSString *mainCharacter = [sakura valueForKey:@"characterName"];
    NSNumber *mainCharCards = [sakura valueForKey:@"ownedClowCards"];

    NSString *rival = [shaoran valueForKey:@"characterName"];
    NSNumber *rivalCards = [shaoran valueForKey:@"ownedClowCards"];

    NSLog(@"%@ has %d Clow Cards", mainCharacter, [mainCharCards intValue]);
    NSLog(@"%@ has %d Clow Cards", rival, [rivalCards intValue]);

    [sakura setValue:[NSNumber numberWithInt:22] forKey:@"ownedClowCards"];
}

就像你可以看到它真的是非常基本的代码一样,所以我感到很惭愧,无论出于什么原因我都无法工作。我正在尝试做的一切就是在拥有的CoreCards更改时收到通知。我正在注册观察员。当我运行程序时,我希望程序运行完毕后会看到“已更改”消息。但它永远不会。更改永远不会打印到我的程序中,所以我假设observeValueForKeyPath:ofObject:change:context:没有被调用。

任何帮助?

2 个答案:

答案 0 :(得分:4)

将观察者添加到尚不存在的对象中。

Character *sakura;

这只是声明变量,但实际上并没有分配或初始化它。

在注册观察员之前尝试调用sakura = [[Character alloc] init];

NSString属性通常使用copy标志,而不是retain。在基本类型(assign)的情况下,内存管理标志(NSInteger)没有意义。

答案 1 :(得分:4)

[sakura addObserver:sakura forKeyPath:@"ownedClowCards" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

在初始化樱花之前,您正在执行上述操作。当然设置nil来观察nil的变化什么都不做。