NSTextView,绑定并显示NSString

nat*_*ate 8 macos xcode cocoa objective-c

我和Cocoa合作的第二天.我已经设置了NSTextView,其属性字符串绑定到NSArrayController(我正在使用Core Data):

controller key: selection
model key path: myString
Run Code Online (Sandbox Code Playgroud)

我已经读过NSTextView需要一个NSAttributedString,这就是为什么它在尝试设置属性的值时抛出异常.

NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "myString"; desired type = NSString; given type = NSConcreteAttributedString; 
Run Code Online (Sandbox Code Playgroud)

任何想法如何让我的managedObject的NSString属性显示在NSTextView中?

dch*_*est 17

您可以将NSString绑定到NSTextView value而不是attributedString.为此,您需要为NSTextView关闭"Rich Text".

  • 是.正如文档中所述,值绑定仅在文本视图使用单个字体时可用. (2认同)

War*_*ton 4

您可以使用 NSValueTransformer 子类来回切换

@interface XXStringTransformer: NSValueTransformer {}
@end

@implementation XXStringTransformer
+ (Class)transformedValueClass 
{   
    return [NSAttributedString class]; 
}
+ (BOOL)allowsReverseTransformation 
{ 
    return YES; 
}
- (id)transformedValue:(id)value 
{
    return (value == nil) ? nil : [[[NSAttributedString alloc] initWithString:value] autorelease];
}

- (id)reverseTransformedValue:(id)value
{
    return (value == nil) ? nil : [[(NSAttributedString *)value string] copy];
}

@end
Run Code Online (Sandbox Code Playgroud)

买者自负- 这可能会颠倒并且反向器可能会泄漏。我现在刚刚成功,但它应该为您指明正确的方向。让我知道,如果答案有误,我会更正。

您可以在绑定面板中键入类名称XXStringTransformer或以编程方式执行。