我正在尝试使用 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"];
}

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

有什么帮助吗?

最佳答案

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

Character *sakura;

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

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

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

关于objective-c - 当值改变时 KVO 不触发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12408923/

10-11 19:48