DOOManiac
DOOManiac

Reputation: 6284

Automatically trim NSString in custom setter?

I have an object w/ an NSString for a property. I would like to use a custom setter for this property so that it always trims all whitespace when the string is set.

Normally this is done with NSString *blah2 = [blah stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];, but I'm not sure about how to formulate this for a custom setter. Isn't it bad to use autoreleased objects like this in the setter? Should I use a mutable string instead and then convert it to unmutable?

Thanks for any help you guys can provide.

Upvotes: 0

Views: 494

Answers (1)

FluffulousChimp
FluffulousChimp

Reputation: 9185

I'm going to presume ARC.

#import <Foundation/Foundation.h>

@interface Foo:NSObject
@property (nonatomic,copy) NSString *myString;
@end

@implementation Foo
@synthesize myString = _myString;

- (void)setMyString:(NSString *)aString;
{
    _myString = [[aString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] copy];
}

@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        Foo *someFoo = [[Foo alloc] init];
        someFoo.myString = @"Blah     ";
        NSLog(@"Length = %ld",[[someFoo myString] length]);  // prints 4
    }
}

In the setter, I do copy the parameter of the setter in the event someone tries to provide an instance of NSMutableString - presuming that Foo is not expected to modify the original string.

EDIT: Or if manual reference counting, the setter might be:

- (void)setMyString:(NSString *)aString;
{
    if( aString != _myString ) {
        [_myString release];
        _myString = [[aString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] copy];
    }
}

Upvotes: 3

Related Questions