为什么 UITextView 使用字符串而不是可变字符串作为其文本属性?
从代码设计的角度来看,为什么 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从一般编码的角度来看:
设置属性时,会调用属性设置方法。 这样,控件能够注意到属性何时更改,以便它可以使用新内容重新绘制控件。
如果该属性是一个可变对象,您可以更改其内容,并且控件不会收到任何发生这种情况的通知,因此它不知道控件需要重新绘制。
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.
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.
当然,您没有理由不能更改它所指向的内容! 因为该成员只是一个指针,所以如果需要,您可以自己用
NSMutableString
替换该字符串。如果您想将大量文本附加到视图中,这可能是一种更有效的方法。
请务必仍然调用 setText ,因为正如 @Guffa 在他的回答中解释的那样,否则视图将不知道如何重绘自身。
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.
Just be sure to still call setText to because as @Guffa explained in his answer, otherwise the view won't know to redraw itself.