Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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!    
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top