我有两难,我似乎无法解决。我已经通过绑定到模型上的属性来应用一些KVO,但是,因为我没有通过点符号分配,所以KVO不会被解雇。相反,我追加像这样:NSMutableAttributedString KVO未触发通知
[[self messagesString] appendAttributedString:attrVal];
messagesString
是NSMutableAttributedString
。当然这不会启动KVO通知,所以我反而做了以下操作:
[self willChangeValueForKey:@"messagesString"];
[[self messagesString] appendAttributedString:attrVal];
[self didChangeValueForKey:@"messagesString"];
但我没有这个运气。如果我做到以下几点:
NSAttributedString *attrVal = [[NSAttributedString alloc] initWithString:str];
[self willChangeValueForKey:@"messagesString"];
[[self messagesString] appendAttributedString:attrVal];
[self didChangeValueForKey:@"messagesString"];
messagesString = [[NSMutableAttributedString alloc] initWithAttributedString:messagesString];
然后正常工作。但是,如果我删除附加行,它不起作用。看来它必须按照这个顺序,包括这些东西,才能起作用。
我错过了如此明显的启动KVO通知?
编辑
所以,我撕了,从这个类声明的任何不相关的东西,但这里的主要原因之一,我指的是:
#import <Foundation/Foundation.h>
@interface Channel : NSObject {
NSString* name;
NSMutableAttributedString *messagesString;
}
@property (retain) NSString* name;
@property (retain) NSMutableAttributedString* messagesString;
- (id)initWithName:(NSString*)name;
- (void)appendString:(NSString*)str;
@end
和实现
#import "Channel.h"
@implementation Channel
@synthesize name;
@synthesize messagesString;
- (id)initWithName:(NSString *)channelName {
self = [super init];
if (self)
{
[self setName:channelName];
messagesString = [[NSMutableAttributedString alloc] initWithString:@" "];
}
return self;
}
- (void)appendString:(NSString *)str {
NSAttributedString *attrVal = [[NSAttributedString alloc] initWithString:str];
[self willChangeValueForKey:@"messagesString"];
[[self messagesString] appendAttributedString:attrVal];
[self didChangeValueForKey:@"messagesString"];
messagesString = [[NSMutableAttributedString alloc] initWithAttributedString:messagesString];
}
@end
我做initWithString
为NSMutableAttributedString
,因为你有一些古怪的方式,你使用我这个类的实例,如果它没有一个空字符串的话(appendAttributedString
如果在实例化时没有设置任何值,就会有问题)。
这是一个字符串是如何追加到它在一个完全独立的类:
Channel *c = [channels valueForKey:@"server"];
[c appendString:val];
最后,我的UI具有对属性串财产NSTextView
绑定去self.currentChannel.messagesString
。此刻我不在我的Mac上,所以我无法显示这些位。
在我的Channel
类中的appendString
方法看起来像是因为我正忙着让它工作。非常多玩代码。
messageString的属性声明是什么? – 2012-08-03 20:23:51
你可以发布你的观察设置调用和观察变化的方法吗? – 2012-08-05 15:29:18
@BrianPalma我更新后的帖子显示了这一点。 – Kezzer 2012-08-06 07:56:02