Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27133

Define macro expected expression issues

I want to create an macro for trimming my string.

I use this code below for trimming:

[[NSString stringWithString:string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]]

But if I create macro as below I get an error: expected expression

#define TRIM_STRING(string) ([[NSString stringWithString:string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]])

How to correctly create same define macro?

Upvotes: 0

Views: 2952

Answers (2)

joerick
joerick

Reputation: 16448

As a macro:

#define TRIM_STRING(string) [(string) stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]

However, there's really no reason not to use an inline function here. You get type checking, and the compiler will give you error messages that make sense. The same as an inline function:

NSString * NSStringTrim(NSString *string)
{
    return [string stringByTrimmingCharactersInSet:
            [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

Or, even better, create a category on NSString for this:

@interface NSString (additions)

- (NSString *)stringByTrimmingWhitespace;

@end

@implementation NSString (additions)

- (NSString *)stringByTrimmingWhitespace
{
    return [self stringByTrimmingCharactersInSet:
            [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

@end

This way you get namespacing, and you can call it by doing

[string stringByTrimmingWhitespace]

which is neater and more consistent with Cocoa.

Upvotes: 3

Extra Savoir-Faire
Extra Savoir-Faire

Reputation: 6036

Get rid of your starting and ending brackets. You've one pair too many.

Then get rid of "NSString stringWithString:string" and replace it with string. This was in itself erroneous because you didn't have it in brackets, but it's academic; you don't need to make a copy of the string anyway.

Edit:

It's a good idea, as your argument to your macro is in parentheses, to place it in parentheses wherever it occurs in your macro. This can avoid problems (if you specify a complex expression as an argument) as the preprocessor expands your macro.

Upvotes: 2

Related Questions