Summary of string concatenation in Objective C
- 2020-05-14 04:58:50
- OfStack
In java and c#, concatenation of strings is done directly with +. In OC, there are three ways to say,
NSString * string; // result string
NSString * string1 string2; // existing string, string1 and string2 need to be concatenated
Method 1:
string = [NSString initWithFormat:@"%@,%@", string1, string2 ];
Method 2:
string = [string1 stringByAppendingString:string2];
Method 3:
string = [string stringByAppendingFormat:@"%@,%@",string1, string2];
The saying on the Internet is that the second method is more efficient 1 point, but I can't feel what comes out, the specific situation is treated well.
Concatenate string in macro:
// Official server
#define API_DOMAIN @"www.ofstack.com"
// Test server
//#define DOMAINXX @"192.168.0.10"
#define API_SYSTEM @"http://"API_DOMAIN@"/system/"
#define API_USER @"http://"API_DOMAIN@"/user/"
The API_SYSTEM macro expands to:
@"http://"@"www.ofstack.com"@"/system/"
The compiler will automatically connect the characters to achieve the purpose.
Implementation in c language:
// Official server
#define API_DOMAIN "www.ofstack.com"
// Test server
//#define DOMAINXX "192.168.0.10"
#define API_SYSTEM "http://"API_DOMAIN"/system/"
#define API_USER "http://"API_DOMAIN"/user/"