View Full Version : Application crashing due to unicode characters in string

Dec 1, 2010, 08:23 AM
Hi all,

I am making an application in which I have to store data from remote db into local sqlite3 db.

Problem is - when any string to be inserted contains unicode character such as: \U00a0 or \U2022 or \U2019, it crashes.

The part of code which crashes is this-

NSString *insertQuery = @"insert into XYZ(field1,field2) values (@"1",[recordDict objectForKey:@"field2"]);

// recordDict contains value: @"\U00a0 \U00a0 \U00a0 \U00a0The Cadfsdfsdfptain\U2019s" for key: @"field2"

sqlite3_stmt *insertStmnt;
const char *sql = [insertQuery cStringUsingEncoding:1];

printf("insertQuery - %s",sql); // it is showing insertQuery - (null) and crashing at next line
if(sqlite3_prepare_v2(database, sql, -1, &insertStmnt, NULL) != SQLITE_OK){
NSLog(@"Error while creating insert statement. '%s'",sqlite3_errmsg(database));

Can anyone suggest me how to resolve this problem?



Dec 1, 2010, 08:30 AM
OK, before we start don't use 1 as the parameter to cStringUsingEncoding:. Use one of the named constants instead.

You can check if a string can be converted to a C-String in a particular encoding using canBeConvertedToEncoding:. If this returns NO you can only turn this into a C-String using a lossy conversion or using a different encoding. The encoding you have specified is NSASCIIStringEncoding which is described in the documentation as:

"Strict 7-bit ASCII encoding within 8-bit chars; ASCII values 0127 only."

Clearly you cannot ever expect your Unicode characters to be representable in this encoding.

Dec 1, 2010, 08:33 AM
On top of what robbieduncan said, the first line doesn't even compile for me. it seems like you trying to use a sort of perl-ism in pulling variables into a string literal, or something like that.