KVC/KVO和绑定:为什么我只收到一个更改通知?

e.J*_*mes 2 cocoa key-value-observing key-value-coding cocoa-bindings

我看到了Cocoa的KVC/KVO和绑定的一些古怪行为.我有一个NSArrayController对象,它的'content'绑定到一个NSMutableArray,我有一个控制器注册为该arrangedObjects属性的观察者NSArrayController.通过此设置,我希望每次修改阵列时都会收到KVO通知.但是,似乎KVO通知仅发送一次; 第一次修改数组.

我在Xcode中设置了一个全新的"Cocoa Application"项目来说明问题.这是我的代码:

BindingTesterAppDelegate.h

#import <Cocoa/Cocoa.h>

@interface BindingTesterAppDelegate : NSObject <NSApplicationDelegate>
{
    NSWindow * window;
    NSArrayController * arrayController;
    NSMutableArray * mutableArray;
}
@property (assign) IBOutlet NSWindow * window;
@property (retain) NSArrayController * arrayController;
@property (retain) NSMutableArray * mutableArray;
- (void)changeArray:(id)sender;
@end
Run Code Online (Sandbox Code Playgroud)

BindingTesterAppDelegate.m

#import "BindingTesterAppDelegate.h"

@implementation BindingTesterAppDelegate

@synthesize window;
@synthesize arrayController;
@synthesize mutableArray;

- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
    NSLog(@"load");

    // create the array controller and the mutable array:
    [self setArrayController:[[[NSArrayController alloc] init] autorelease]];
    [self setMutableArray:[NSMutableArray arrayWithCapacity:0]];

    // bind the arrayController to the array
    [arrayController bind:@"content" // see update
                 toObject:self
              withKeyPath:@"mutableArray"
                  options:0];

    // set up an observer for arrangedObjects
    [arrayController addObserver:self
                      forKeyPath:@"arrangedObjects"
                         options:0
                         context:nil];

    // add a button to trigger events
    NSButton * button = [[NSButton alloc]
                         initWithFrame:NSMakeRect(10, 10, 100, 30)];
    [[window contentView] addSubview:button];
    [button setTitle:@"change array"];
    [button setTarget:self];
    [button setAction:@selector(changeArray:)];
    [button release];

    NSLog(@"run");
}

- (void)changeArray:(id)sender
{
    // modify the array (being sure to post KVO notifications):
    [self willChangeValueForKey:@"mutableArray"];
    [mutableArray addObject:[NSString stringWithString:@"something"]];
    NSLog(@"changed the array: count = %d", [mutableArray count]);
    [self didChangeValueForKey:@"mutableArray"];
}

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

- (void)applicationWillTerminate:(NSNotification *)notification
{
    NSLog(@"stop");
    [self setMutableArray:nil];
    [self setArrayController:nil];
    NSLog(@"done");
}

@end
Run Code Online (Sandbox Code Playgroud)

这是输出:

load
run
changed the array: count = 1
arrangedObjects changed!
changed the array: count = 2
changed the array: count = 3
changed the array: count = 4
changed the array: count = 5
stop
arrangedObjects changed!
done
Run Code Online (Sandbox Code Playgroud)

如您所见,KVO通知仅在第一次发送时(当应用程序退出时再次发送).为什么会这样呢?

更新:

感谢orque指出我应该绑定contentArray我的NSArrayController,而不仅仅是它content.只要进行了此更改,上面发布的代码就会起作用:

// bind the arrayController to the array
[arrayController bind:@"contentArray" // <-- the change was made here
             toObject:self
          withKeyPath:@"mutableArray"
              options:0];
Run Code Online (Sandbox Code Playgroud)

orq*_*que 7

首先,您应该绑定到contentArray(而不是内容):

    [arrayController bind:@"contentArray"
             toObject:self
          withKeyPath:@"mutableArray"
              options:0];
Run Code Online (Sandbox Code Playgroud)

然后,直接的方法是只使用arrayController来修改数组:

- (void)changeArray:(id)sender
{
    // modify the array (being sure to post KVO notifications):
    [arrayController addObject:@"something"];
    NSLog(@"changed the array: count = %d", [mutableArray count]);
}
Run Code Online (Sandbox Code Playgroud)

(在实际场景中,您可能只希望按钮操作调用-addObject :)

使用 - [NSMutableArray addObject]不会自动通知控制器.我看到你试图通过在mutableArray上手动使用willChange/didChange来解决这个问题.这不起作用,因为数组本身没有改变.也就是说,如果KVO系统在更改之前和之后查询mutableArray,它仍将具有相同的地址.

如果你想使用 - [NSMutableArray addObject],你可以在arrangeObjects上更改/ didChange:

- (void)changeArray:(id)sender
{
    // modify the array (being sure to post KVO notifications):
    [arrayController willChangeValueForKey:@"arrangedObjects"];
    [mutableArray addObject:@"something"];
    NSLog(@"changed the array: count = %d", [mutableArray count]);
    [arrayController didChangeValueForKey:@"arrangedObjects"];
}
Run Code Online (Sandbox Code Playgroud)

可能会有一个更便宜的密钥,可以产生相同的效果.如果您有选择,我建议您只使用控制器并将通知留给底层系统.


Pet*_*sey 5

比显式发布整值KVO通知更好的方法是实现数组访问器并使用它们.然后KVO免费发布通知.

那样,而不是这个:

[self willChangeValueForKey:@"things"];
[_things addObject:[NSString stringWithString:@"something"]];
[self didChangeValueForKey:@"things"];
Run Code Online (Sandbox Code Playgroud)

你会这样做:

[self insertObject:[NSString stringWithString:@"something"] inThingsAtIndex:[self countOfThings]];
Run Code Online (Sandbox Code Playgroud)

KVO不仅会为您发布更改通知,而且它将是一个更具体的通知,即数组插入更改而不是整个数组更改.

我通常会添加一个addThingsObject:执行上述操作的方法,以便我可以执行以下操作:

[self addThingsObject:[NSString stringWithString:@"something"]];
Run Code Online (Sandbox Code Playgroud)

请注意,add<Key>Object:当前不是KVC认可的数组属性的选择器格式(仅设置属性),而是insertObject:in<Key>AtIndex:,因此您对前者的实现(如果您选择这样做)必须使用后者.