为什么 UITextView 使用字符串而不是可变字符串作为其文本属性?

发布于 2024-07-21 13:55:34 字数 119 浏览 0 评论 0原文

从代码设计的角度来看,为什么 UITextView 的内部实现使用 NSString 而不是 NSMutableString 当其内容经常更改时?

Any idea from a code design standpoint why does the internal implementation of UITextView uses an NSString but not an NSMutableString when its content is meant to change often?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

古镇旧梦 2024-07-28 13:55:34

从一般编码的角度来看:

设置属性时,会调用属性设置方法。 这样,控件能够注意到属性何时更改,以便它可以使用新内容重新绘制控件。

如果该属性是一个可变对象,您可以更改其内容,并且控件不会收到任何发生这种情况的通知,因此它不知道控件需要重新绘制。

From a general coding point of view:

When setting a property the property setter method is called. That way the control is able to notice when the property is changed, so that it can redraw the control with the new content.

If the property is a mutable object, you can change its contents and the control will not get any notification that this has happened, so it doesn't know that the control needs to be redrawn.

伪心 2024-07-28 13:55:34

Cocoa 中的通用模式是传递不可变对象,而不是允许外部类访问私有可变变量。 您会在 NSArray 和 NSDictionary 等集合类中看到同样的情况。

It's a general pattern in Cocoa to pass around immutable objects instead of allowing outside classes access private mutable variables. You'll see the same thing with collections classes like NSArray and NSDictionary.

我偏爱纯白色 2024-07-28 13:55:34

当然,您没有理由不能更改它所指向的内容! 因为该成员只是一个指针,所以如果需要,您可以自己用 NSMutableString 替换该字符串。

如果您想将大量文本附加到视图中,这可能是一种更有效的方法。

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [myTextView setText:[[NSMutableString alloc] init]];
    }
    return self;
}

请务必仍然调用 setText ,因为正如 @Guffa 在他的回答中解释的那样,否则视图将不知道如何重绘自身。

- (void)appendText:(NSString*)text 
{
    NSMutableString *dispText = (NSMutableString*)[myTextView text];
    [dispText appendString:text];

    [myTextView setText:dispText]; // notify myTextView of text change!    
}

Of course, there's no reason you can't change what it points to! Because the member is just a pointer, you can replace the string with an NSMutableString yourself if you want.

This might be a more efficient approach if you want to append a lot of text to the view.

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [myTextView setText:[[NSMutableString alloc] init]];
    }
    return self;
}

Just be sure to still call setText to because as @Guffa explained in his answer, otherwise the view won't know to redraw itself.

- (void)appendText:(NSString*)text 
{
    NSMutableString *dispText = (NSMutableString*)[myTextView text];
    [dispText appendString:text];

    [myTextView setText:dispText]; // notify myTextView of text change!    
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文