什么是附加到NSString的推荐方式

问题描述:

我正在执行一些字符串连接来创建数据库查询。 作为其中的一部分,我需要分配并重新分配NSString变量以附加到它。什么是附加到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 %@ 
+0

为什么要先分配初始化retVal并重新分配给它? – 2012-12-09 21:16:12

+0

我复制并运行了你的代码,它对我来说工作得很好 - 你在哪里运行你的代码?其他的东西是否可以将retVal设置为空字符串? – redlightbulb

+0

对我来说工作也很好。你在哪里登录?我猜测retVal在您检查时已被释放。 – rdelmar

要么使用一个NSMutableStringappendString:,使用stringByAppendingString:,或用单stringWithFormat:构建完整的字符串,在你需要的所有值堵漏立刻。

+0

现在的问题是_注意每当retVal和concat保持“”(空字符串)时,我会在retVal中返回空字符串。这绝对不是我所期待的,因为我应该得到“myfield ='myvalue'”._ OP已经知道如何附加字符串。 – iDev

+0

这段代码给了我日志中的空字符串:NSMutableString * retVal = [[NSMutableString alloc] init]; [retVal appendString:@“mystring”]; NSLog(@“%@”,retVal); –

+0

这种方法有效。问题是,我在if-else块内移动指令指针。当我直接运行代码时,它工作正常。指针的移动绝对与我所搞乱的任何字符串没有关系,但它影响了串联的字符串。可能在LLDB中存在一个错误。 –

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];