Shortcuts in Objective-C to concatenate NSStrings

前端 未结 30 2878
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 07:03

Are there any shortcuts to (stringByAppendingString:) string concatenation in Objective-C, or shortcuts for working with NSString in general?

30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 07:43

    This is for better logging, and logging only - based on dicius excellent multiple argument method. I define a Logger class, and call it like so:

    [Logger log: @"foobar ", @" asdads ", theString, nil];
    

    Almost good, except having to end the var args with "nil" but I suppose there's no way around that in Objective-C.

    Logger.h

    @interface Logger : NSObject {
    }
    + (void) log: (id) first, ...;
    @end
    

    Logger.m

    @implementation Logger
    
    + (void) log: (id) first, ...
    {
        // TODO: make efficient; handle arguments other than strings
        // thanks to @diciu http://stackoverflow.com/questions/510269/how-do-i-concatenate-strings-in-objective-c
        NSString * result = @"";
        id eachArg;
        va_list alist;
        if(first)
        {
            result = [result stringByAppendingString:first];
            va_start(alist, first);
            while (eachArg = va_arg(alist, id)) 
            {
                result = [result stringByAppendingString:eachArg];
            }
            va_end(alist);
        }
        NSLog(@"%@", result);
    }
    
    @end 
    

    In order to only concat strings, I'd define a Category on NSString and add a static (+) concatenate method to it that looks exactly like the log method above except it returns the string. It's on NSString because it's a string method, and it's static because you want to create a new string from 1-N strings, not call it on any one of the strings that are part of the append.

提交回复
热议问题