【发布时间】:2014-08-26 21:17:31
【问题描述】:
当我更改字符串时,绑定到 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)] );
}
【问题讨论】:
-
尝试使用 mutLabel.string,而不是 mutLabel? KVC 查找 setter/getter 调用,因此 setString/string 基本上是可变字符串对象上字符串“property”的访问器。
-
@stevesliva :试过了,但我崩溃了。“类不是键值编码投诉”
-
嗯。这很烦人。 (因为没有一个类同时支持 setter 和 getter?)this question 的重复,顺便说一句。虽然我不确定我是否喜欢这些答案。当绑定正在寻找设置器时,您可能会收到该错误消息——也许尝试将 mutLabel.string 绑定到按钮的标题或某些工具提示。只读绑定可能有效。如果单向绑定有效,那么可能有一种方法可以让值绑定永远不会寻找 setter。
标签: objective-c cocoa nsmutablestring