0

我现在正在学习键值观察,有一个非常简单的 KVO 项目有一个小问题,即在observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context方法调用时不打印属性新值的变化。这很奇怪,希望有人帮我找出问题所在,我非常感谢!

这是我的源代码:

视图控制器.h

#import <UIKit/UIKit.h>

@class Person;

@interface ViewController : UIViewController

@property (nonatomic, strong) Person *person;

@end

视图控制器.m

#import "ViewController.h"
#import "Person.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize person;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.person = [[Person alloc] init];
    [self changeName];
    [self.person addObserver:self
             forKeyPath:@"fullName"
                options:NSKeyValueObservingOptionNew
                context:NULL];
}

- (void)changeName
{
    self.person.fullName = @"Andy";
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if ([keyPath isEqualToString:@"fullName"])
    {
        NSLog(@"%@", change);
        NSString *string = [change objectForKey:NSKeyValueChangeNewKey];
        NSLog(@"%@", string);
    }
}

- (void)dealloc
{
    [self.person removeObserver:self forKeyPath:@"fullName"];
}

@end

人.h

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property (nonatomic, strong) NSString *fullName;

@end

人.m

#import "Person.h"

@implementation Person

@synthesize fullName = _fullName;

@end
4

2 回答 2

1

在添加观察者之前更改名称。交换这个:

[self changeName];
[self.person addObserver:self
         forKeyPath:@"fullName"
            options:NSKeyValueObservingOptionNew
            context:NULL];

...为了这:

[self.person addObserver:self
         forKeyPath:@"fullName"
            options:NSKeyValueObservingOptionNew
            context:NULL];
[self changeName];
于 2013-05-28T16:17:37.137 回答
1

看看你的通话顺序,

您在注册为观察员changeName 之前打电话。

changeName调用移到方法下方addObserver,看看会发生什么。

于 2013-05-28T16:17:38.547 回答