字符串、数组拼接注意事项
字符串拼接2种方法
- (NSString *)stringByAppendingString:(NSString *)aString;
- (NSString *)stringByAppendingFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
<br />
苹果官方文档给出的例子
1、被拼接字符串对象的值是nil
// str2 拼接到str
NSString *str1 = nil;
NSString *str2 = @"abc";
NSString *str3 = [str1 stringByAppendingString:str2];
NSString *str4 = [str1 stringByAppendingFormat:@"%@",str2];
NSLog(@"%@ %@",str
log 输出
appendStringDemo[2495:281074] (null) (null)
2、被拼接字符串对象的值是"hello "
NSString *string1 = @"hello ";
NSString *string2 = @"world.";
NSString *string3 = [string1 stringByAppendingString:string2];
NSString *string4 = [string1 stringByAppendingFormat:@"%@",string2];
NSLog(@"%@ %@",string3,string4);
log 输出
appendStringDemo[2495:281074] hello world. hello worl.
** 注意 **<br />
- 字符串拼接,被拼接对象的值不能是nil
- 数组的拼接和字符串拼接同理,被拼接对象不能是nil ,下面给出2个方法
- (NSArray *)arrayByAddingObject:(id)anObject;
- (NSArray *)arrayByAddingObjectsFromArray:(NSArray *)otherArray;
网友评论