Either use an NSMutableString
with appendString:
, use stringByAppendingString:
, or construct the full string with a single stringWithFormat:
, plugging in the values you need all at once.
What is the recommended way to append to NSString
-
06-12-2021 - |
質問
I am performing some string concatenation to create a database query. As part of this, I need to assign and re-assign NSString variable in order to append to it.
I am currently using this code:
NSString *retVal = [[NSString alloc]init];
NSString *concat = @"";
retVal = [NSString stringWithFormat:@"%@%@ myfield= 'myvalue'", retVal, concat];
Note that whenever retVal and concat hold "" (empty string), I get empty string back in retVal. This is definitely not expected as I should get " myfield= 'myvalue'".
What am I missing?
Update:
Here is last I tried:
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 %@
解決 2
他のヒント
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];
所属していません StackOverflow