matttrakker
matttrakker

Reputation: 204

Self assignment for NSString category

I want to self assign an adjusted nsstring via category. The example is a trim function:

I do not want that way:

NSString *theTempString = [theExampleString xTrim];
// ... go on doing stuff with theTempString

I want it this way:

[theExampleString xTrim];
// ... go on doing stuff with theExmapleString

The category looks like this:

- (void)xTrim
{
    self = [self stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

}

The error that an assignment outside init is not possible - I understand that. But now I'm interested in it, of course I can write an custom init methode, but is there no way around it like the one above???

Greetings and thanks,

matthias

Upvotes: 0

Views: 585

Answers (2)

Martin R
Martin R

Reputation: 539795

You cannot do that in a category on NSString, because NSString manages immutable strings, which means that the string can not be changed after it has been created.

You could implement it as category on NSMutableString:

- (void)xTrim
{
    NSString *trimmed = [self stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
    [self setString:trimmed]; // replaces the characters of "self" with those of "trimmed".
}

And if your question is: Can I write a method xTrim such that

[theExampleString xTrim]

replaces the receiver theExampleString with a new instance: No, that is not possible.

Upvotes: 3

hwaxxer
hwaxxer

Reputation: 3383

You don't need to create a new NSString, the method already does that for you:

- (NSString *)xTrim
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

NSString is immutable so you need to assign it:

yourString = [yourString xTrim];

Upvotes: 3

Related Questions