Shortcuts in Objective-C to concatenate NSStrings

前端 未结 30 2897
伪装坚强ぢ
伪装坚强ぢ 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:57

    My preferred method is this:

    NSString *firstString = @"foo";
    NSString *secondString = @"bar";
    NSString *thirdString = @"baz";
    
    NSString *joinedString = [@[firstString, secondString, thirdString] join];
    

    You can achieve it by adding the join method to NSArray with a category:

    #import "NSArray+Join.h"
    @implementation NSArray (Join)
    -(NSString *)join
    {
        return [self componentsJoinedByString:@""];
    }
    @end
    

    @[] it's the short definition for NSArray, I think this is the fastest method to concatenate strings.

    If you don't want to use the category, use directly the componentsJoinedByString: method:

    NSString *joinedString = [@[firstString, secondString, thirdString] componentsJoinedByString:@""];
    

提交回复
热议问题