如何将const char连接到const char?

时间:2011-11-20 20:16:51

标签: objective-c cocoa-touch nsstring string-concatenation

我需要建立const char其他const char的字符串吗?

const char *sql = "";
const char *sqlBuild = "";

for(int i=0; i < ac_count; ++i) {

  if (![sqlBuild isEqualToString:@""]) {
     sqlBuild = [sqlBuild stringByAppendingString:
           [NSString stringWithUTF8String:@" UNION "]];
  }
  sql = [[NSString stringWithFormat:
      @"select sum(price) from tmp%d  where due >= date() and due <= '%@'",  
            i, strDBDate] cStringUsingEncoding:NSUTF8StringEncoding];

  sqlBuild = [sqlBuild stringByAppendingString:
       [NSString stringWithUTF8String:sql]];
}

//execute sql

我有过几次尝试,但是不能完全正确,这是我最后的尝试。正如您所看到的,我正在尝试构建一个sql语句。

我哪里错了?

编辑 - 我正在使用不喜欢NSString的sql lite,见下文。

- (NSString*)getCategoryDesc:(int)pintCid {

NSString *ret = @"";
const char *sql = "select category from categories where cid = ?";

sqlite3 *database;
int result = sqlite3_open([[General getDBPath] UTF8String], &database);
if(result != SQLITE_OK)
{
    DLog(@"Could not open db.");
}

sqlite3_stmt *statementTMP;

int error_code = sqlite3_prepare_v2(database, sql, -1, &statementTMP, NULL);

if(error_code == SQLITE_OK) {

    sqlite3_bind_int(statementTMP, 1, pintCid);

    if (sqlite3_step(statementTMP) == SQLITE_ROW) {
        ret = [[NSString alloc] initWithUTF8String:
            (char *)sqlite3_column_text(statementTMP, 1)];
    }
}
sqlite3_finalize(statementTMP);
sqlite3_close(database);


return [ret autorelease];
}

2 个答案:

答案 0 :(得分:3)

转换为UTF8字符串然后从UTF8字符串转换没有任何好处;在NSString中执行所有操作并在结尾处将其转换为C风格的字符串会更有效。 @"d"语法也计算为对象,而不是C样式的字符串。

因此,您应该简化并更正您的代码:

NSMutableString *sqlStatement = [NSMutableString string];

for(int i=0; i < ac_count; ++i) {

  if ([sqlStatement length])  [sqlStatement appendString:@" UNION "];

  [sqlStatement appendFormat:
      @"select sum(price) from tmp%d  where due >= date() and due <= '%@'",  
            i, strDBDate];

}

// execute SQL string [sqlStatement UTF8String]

答案 1 :(得分:2)

sqlBuild声明为NSMutableString并使用它来构建字符串:

NSMutableString *sqlBuild = [NSMutableString string];
for (...) {
    [sqlBuild appendString:...];
}