本文介绍了我如何绑定一个的NSMutableString到NSTextView的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以我试图建立一个非常简单的程序为自己在X $ C $角结果
我有一个包含一个NSTextView,和NSButton窗口(在Interface Builder)。里面我的AppController类,我宣布一个的NSMutableString 作为一个属性。我想要做的是字符串设定的初始值,说@首次进入\\ N的话,它绑定到 NSTextView 。当我按下按钮,方法, - (IBAction为)appendToString 称为其追加 @另一行\\ n的NSMutableString 。结果
我想,然后通过绑定和键值观察,而不是通过声明 IBOutlet中 NSTextView 这些变化C>和手动更新的内容。我也想改变我做的TextView的编辑 NSMutable 字符串。

不幸的是,我非常困惑,和一个没有任何运气搞清楚了这一点。

什么是如何去这几个基本步骤?

的*编辑***

好吧,彼得Hosey间接地解决了这个问题。我忘了,我不得不使用setLogString方法,而不是使用[logString appendFormat:]。因此,这里的code我结束了:

在AppController.h:

 #进口<可可/ Cocoa.h>
@interface AppController的:NSObject的{
    IBOutlet中NSButton * appendButton;
    * NSString的logString;
    IBOutlet中NSTextView * thatView;
}
@property(读写,拷贝)的NSString * logString;
- (IBAction为)hitIt:(ID)发送;
@结束

AppController.m:

 #进口AppController.h
@implementation AppController的
- (无效)awakeFromNib
{
}
- (ID)的init
{
    [超级初始化]
    logString = @行头\\ n;
    返回自我;
}
- (IBAction为)hitIt:(ID)发送者
{
    [个体经营setLogString:[logString stringByAppendingString:@嘿,另一行\\ N]];
}
@synthesize logString;
@结束

然后,在InterfaceBuilder下,我绑定的NSTextView到AppController.logString,并设置了连续更新值标志,这样的变化,我对文本字段将字符串进行。

感谢很多的帮助家伙!


解决方案

This is the correct, MVC-compliant solution. The primary owner of the model should be the controller, not views. All views should obtain the model from the controller.

You should not, however, expose the string's mutability. Anything that uses the property may then attempt to mutate the string directly, without the AppController knowing about the change and being able to notify any observers of the property. The property should be declared as NSString, and as readwrite in order to provide an accessor with which to replace the value with a new string.

Set the value of the instance variable backing the property in init.

Bind the NSTextView in IB. Then, it will already be bound when you load the nib.

Note that you want to set the ivar before loading the nib. If you load the nib first, the text view will not see the change, because setting the ivar directly (as you should do in init, to avoid incurring property side-effects) is making the change behind the observer's (view's) back. If the change is already made when you load the nib (and the view starts observing), then there is nothing for the view to miss.

Every action in Cocoa takes exactly one argument—no more, no fewer. That argument is the control that sent the message. Thus, the correct signature is:

- (IBAction) appendToString:(id)sender;

All you need to do is ask the property for your current string, make a mutable copy, make the change, and set the modified string as the new value of the property. Don't forget to release that mutable copy.

Both of these happen for free when you bind the text view's value binding to your AppController's property.

这篇关于我如何绑定一个的NSMutableString到NSTextView的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 22:33