绑定到的NSMutableString财产在厦门国际银行的标签似乎并不当我改变字符串进行更新,但标签不更新,如果该属性是的NSString。
在测试应用程序,我有默认的AppDelegate类和MainMenu.xib。我创建的AppDelegate两个属性,一个的NSString和一个的NSMutableString,并将其绑定到厦门国际银行两个标签。我有两个按钮来改变从一组这些字符串的值到另一个和背部。代码如下所示。的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:
在适当情况下应该是所有的需要在志愿遵守的条款,以支持绑定。然而,据我可以通过实验确定*的文本了AppKit视图(NSTextField
和NSTextView
),文本内容将不会更新,如果他们绑定到的属性指的是同一个对象前和更新后。实验表明观察发生的事情,但被忽略;据推测,该视图包含逻辑,以避免不必要的更新。
总之,NSTextView
和NSTextField
的绑定与NSMutableString
突变不兼容。除非你有其他的理由要使用可变的字符串,你还不如用一成不变的版本坚守。
*了AppKit似乎并不包括苹果的开源版本中,所以检查的来源是不是一种选择。