Question

I am learning how to use macro but now confused with one.

I am trying to create a NSString concatenate which will just append every params to each other.

for example : concatOP(@"hey",@"Jude",@"Don't") would return a NSString containing : @"heyJudeDon't"

I actually made a bit of code (some found here as well) which get the number of params but I don't succeed to make the second part of the job.

#define NUMARGS(...)        ( sizeof((int[]){__VA_ARGS__}) / sizeof(int) )
#define concatOP(...)       NSMutableString *format = [[NSMutableString alloc] init];\
                            for( int i = 0; i < NUMARGS(__VA_ARGS__); i++){\
                            [format appendString:@"%@"];}\
                            [[NSString alloc] initWithFormat:format, __VA_ARGS__]

I actually get many errors, telling me that format doesn't exist or that I miss some ";" or other ending tags.

Was it helpful?

Solution

Here is yours macro:

#define concatOP(...) [@[__VA_ARGS__] componentsJoinedByString:@""]

EDIT: if you unwind yours macro NSString* result = concatOP(@"hey",@"Jude",@"Don't"); you will get:

NSString* result = NSMutableString *format = [[NSMutableString alloc] init]; for( int i = 0; i < NUMARGS(@"hey",@"Jude",@"Don't"); i++){ format = [format appendString:@"%@"];} [[NSString alloc] initWithFormat:format, @"hey",@"Jude",@"Don't"];

Looks odd.

OTHER TIPS

This doesn't exactly answer your question, but NSString literals are concatenated by the compiler, just like their C-counterparts, so this code works out of the box:

NSString *str = @"Hey" @"Jude" @"Don't";

which is the same as:

NSString *str = @"HeyJudeDon't";

This is typically used to split a long string literal across multiple lines of the source file.

Bottom line; you don't need all those messy macros and pointless methods to do this.

I don't know how to do this with macros.

You can do it in Objective C like:

Implement a method like:

- (NSString *)concateStrings:(NSString *)firstArg, ...
{
    NSMutableString *concatString = [[NSMutableString alloc] init];
    va_list args;
    va_start(args, firstArg);
    for (NSString *arg = firstArg; arg != nil; arg = va_arg(args, NSString*))
    {
        [concatString appendString:arg];
    }
    va_end(args);

    return concatString;
}

You can call this method like:

NSLog(@"%@",[self concateStrings:@"hey",@"Jude",@"Don't",nil]) ;

Output:

heyJudeDon't

Make sure that you pass nil at the end.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top