我正在执行一些字符串连接以创建数据库查询。 作为其中的一部分,我需要分配和重新分配 NSString 变量以便附加到它。
我目前正在使用这段代码:
NSString *retVal = [[NSString alloc]init];
NSString *concat = @"";
retVal = [NSString stringWithFormat:@"%@%@ myfield= 'myvalue'", retVal, concat];
请注意,每当 retVal 和 concat 保留“”(空字符串)时,我都会在 retVal 中返回空字符串。这绝对不是预期的,因为我应该得到“myfield='myvalue'”。
我错过了什么?
更新:
这是我最后一次尝试:
NSMutableString * retVal = [[NSMutableString alloc] init];
NSString * concat = @"";
[retVal appendString:@"appendstring"];
NSLog(@"%@", retVal); // prints <object returned empty description>
[retVal appendString:concat];
[retVal appendString:@"appendstring1"];
NSLog(@"%@", retVal); // prints %@
最佳答案
NSString *retVal = @"";
NSString *concat = @"";
//do whatever stuff you want with retVal and concat
//once finished then do this below
if(retVal.length==0||concat.length==0)
{
retVal = @"myfield= 'myvalue'";
}
else
retVal = [NSString stringWithFormat:@"%@%@ myfield= 'myvalue'", retVal, concat];
关于ios - 附加到 NSString 的推荐方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13791889/