Q:

Using single quote when building a string in Cocoa

I am building a string in Cocoa to be used as a SQL statement which will be passed into the FMDB wrappers for sqlite; however, the database craps out with a BAD_ACCESS failure.  I have the following code:
prefix = @"SELECT * FROM Table WHERE Field1 LIKE '%";
middle = @"%' OR Field2 LIKE '%";
suffix = @"%' ORDERY BY ";
orderby = @"%' ORDER BY Fieldnames";
sqlStatement = [NSString stringWithFormat:@"%@%@%@%@%@%@", prefix, searchString, middle, searchString, suffix, orderby];
At runtime sqlStatement ends up containing something like the following:
SELECT * FROM Table WHERE Field1 LIKE \'%A%\' OR Field2 LIKE \'%A%\' ORDER BY Fieldnames
For some reason a \ is being added into the string which causes the database to bomb out.  
Any ideas how I can keep the \ from appearing in my string?
UPDATE:
When I output my variable via NSLog I get the following: 
SELECT * FROM Table WHERE Field1 LIKE 'OX1.87A8013DBD18F-1027' OR Field2 LIKE 'OX1.87A8013DBD18F-1027'ORDER BY Fieldname. 
Problem seems to be with using %A in the string.  Even if I hard code the sqlStatement variable to include '%A%' the %A seems to get converted to a memory address or something.  If I do a '%ABAP%' I get the output like 'OX1.87A8013DBD18F-1027BAP'.  Notice i'm losing the % sign.

A:

I'm going to guess that you're using sqlite, in which case you want to do this slightly differently.  First start by creating your query like this:
SELECT * FROM Table WHERE Field1 LIKE ?001 OR Field2 LIKE ?002 ORDER BY Fieldnames

The ?000 syntax is for parameters.
You can then use sqlite3_bind_text to bind your parameters:
sqlite3_bind_text(statement, 1, [@"%bar%" UTF8String], -1, SQLITE_STATIC);
sqlite3_bind_text(statement, 2, [@"%foo%" UTF8String], -1, SQLITE_STATIC); 

Hopefully this should point you in the right direction.

