到XIB的NSMutableString绑定不会更新,但是NSString绑定会更新



绑定到NSMutableString属性的XIB中的标签在我更改字符串时似乎不会更新,但如果属性是NSString,则标签会更新。

在测试应用中,我有默认的AppDelegate类和MainMenu.xib。我在AppDelegate中创建了两个属性,一个NSString和一个NSMutableString,并将它们绑定到XIB中的两个标签。我有两个按钮可以将这些字符串的值从一组更改为另一组,然后再更改回来。代码如下所示。NSLog的输出显示NSMutableString的值在变化,但是没有反映在GUI中。

不知道我错过了什么…任何帮助将不胜感激!

PS:编辑:我想实现这一点,而不创建一个新的可变字符串

代码:

@synthesize mutLabel, unmutLabel;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self willChangeValueForKey:@"mutLabel"];
    mutLabel = [NSMutableString stringWithCapacity:10];
    [mutLabel setString:@"MutLabel 1"];
    [self didChangeValueForKey:@"mutLabel"];
    [self willChangeValueForKey:@"unmutLabel"];
     unmutLabel = @"UnMutLabel 1";
    [self didChangeValueForKey:@"unmutLabel"];
    [self addObserver:self forKeyPath:@"mutLabel" options:0 context:nil];
    [self addObserver:self forKeyPath:@"unmutLabel" options:0 context:nil];
}
- (IBAction)clkBtn1:(id)sender {
    [self willChangeValueForKey:@"mutLabel"];
    [mutLabel setString:@"MutLabel 1"];
    [self didChangeValueForKey:@"mutLabel"];
    [self willChangeValueForKey:@"unmutLabel"];
    unmutLabel = @"UnMutLabel 1";
    [self didChangeValueForKey:@"unmutLabel"];
}
- (IBAction)clkBtn2:(id)sender {
    [self willChangeValueForKey:@"mutLabel"];
    [mutLabel setString:@"MutLabel 2"];
    [self didChangeValueForKey:@"mutLabel"];
    [self willChangeValueForKey:@"unmutLabel"];
    unmutLabel = @"UnMutLabel 2";
    [self didChangeValueForKey:@"unmutLabel"];
}
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"Key change: Key: %@  Value: %@n",keyPath, [self performSelector:NSSelectorFromString(keyPath)]  );
}

删除上面的代码行,只尝试下面的代码行设置字符串在可变和不可变对象,这是绑定到标签。

    NSString * str=@"yourString";
    self.mutLabel=[str mutableString];
    self.unmutLabel=str;

根据文档,在适当的地方调用willChangeValueForKey:didChangeValueForKey:应该是为了支持绑定而遵从KVO所需要的全部。然而,据我所知,通过实验*,AppKit文本视图的文本内容(NSTextFieldNSTextView),不会更新,如果属性,他们被绑定到引用相同的对象之前和之后的更新。实验表明观察发生了,但被忽略了;假设,视图包含逻辑以避免不必要的更新。

简而言之,NSTextViewNSTextField的结合与NSMutableString突变不兼容。除非您有其他理由使用可变字符串,否则您最好还是使用不可变版本。

* AppKit似乎没有包含在苹果的开源版本中,所以检查源代码是不可能的。

最新更新