Forwarding Address: OS X

Monday, November 01, 2004

Obj-C and string concatenation: a question

In my quest to learn Obj-C I was playing around with it and SQLite on the weekend and of course wanted to execute an SQL query against the database:
INSERT INTO tableName ( colA, colB, colC ) VALUES ( 'valA', 'valB', 'valC' );
where valA, valB, and valC are the values of properties extracted from an object. In other languages I'd just concatenate the string (pseudo-code):
sqlStr = "INSERT INTO tableName ( colA, colB, colC ) VALUES ( '" . myObj.ValA . "', '" . myObj.ValB ."'..." 
and so on but in Obj-C I was reduced to using a ton of stringByAppendingString() calls to make this happen, one for each chunk, which becomes very unwieldy very quickly and requires a lot of typing, esp. for large inserts. So my question: is there a better way to concatenate SQL queries in Obj-C? Any suggestions?

5 Comments:

  • Well, you could try stringByAppendingFormat.

    It's still cumbersome though.
    Here's an example of some code we used in Virtual Pet Rock for constructing queryparts in a URL.

    uploadMain = [controlDict valueForKey:@"UploadLocation"];
    uploadMain = [uploadMain stringByAppendingFormat: @"?cn=%@&geboorte=%@&sexe=%@&rockname=%@&version=%@&rockpict=%@", [preferences stringForKey:@"rockCustNo"], [preferences objectForKey:@"rockBirth"], [preferences stringForKey:@"rockSex"], [preferences stringForKey:@"rockName"], currVersionNumber, [preferences stringForKey:@"rockPict"]];

    This will translate into something like www.virtualpetrock.nl/upload.php?cn=xxxxxxxx&geboorte=13-12-2003&sexe=Male& etc.

    Harold.

    By Anonymous, at 9:57 AM  

  • I usually use stringWithFormat: in a manner similar to the about comment when creating queries for sqlite. For your example:

    NSString *query = [NSString stringWithFormat:@"INSERT INTO tableName ( colA, colB, colC ) VALUES ( '%@', '%@' ...", [myObj valA], [myObj valB], ...];

    It performs a lot quicker then a single append, never mind multiple ones strung together, and is a lot less annoying to write.

    Brad

    By Anonymous, at 11:28 AM  

  • Hmm... stringWithFormat... that definitely looks cleaner, or at least less code to write - thanks!

    By Chris, at 3:09 AM  

  • Depending on the exact need I'll often put my substrings into an array with [NSArray arrayWithObjects:...] and then concatenate the strings together with [NSArray componentsJoinedByString:]

    By Anonymous, at 5:43 AM  

  • Over at NSLog() there's more comments on that issue, for those who are following along: http://nslog.com/archives/2004/11/01/objc_string_concat.php.

    And thanks to all who've replied - I've gotten more insight into concatenating strings from these comments than I did from an hour of reading about them online at 4am this morning.

    By Chris, at 7:22 AM  

Post a Comment

<< Home