問題描述
為什麼 UITextView 的 text 屬性使用字符串而不是可變字符串? (Why does UITextView use string rather than mutable string for its text property?)
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?
參考解法
方法 1:
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.
方法 2:
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.
方法 3:
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.
<pre class="lang-c prettyprint-override">- (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [myTextView setText:[[NSMutableString alloc] init]]; } return self; }
</pre>
Just be sure to still call setText to because as @Guffa explained in his answer, otherwise the view won't know to redraw itself.
<pre class="lang-c prettyprint-override">- (void)appendText:(NSString)text
{
NSMutableString dispText = (NSMutableString*)[myTextView text];
[dispText appendString:text];
[myTextView setText:dispText]; // notify myTextView of text change!
}
</code></pre>
(by Boon、Guffa、Marc Charbonneau、NHDaly)
參考文件