由于字符串中的 unicode 字符导致应用程序崩溃
我正在制作一个应用程序,其中必须将远程数据库中的数据存储到本地 sqlite3 数据库中。
问题是 - 当任何字符串是 插入的内容包含 unicode 字符 例如:\U00a0 或 \U2022 或 \U2019, 它崩溃了。
崩溃的代码部分是这样的-
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));
}
任何人都可以建议我如何解决这个问题吗?
谢谢,
米拉杰
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?
Thanks,
Miraaj
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
cStringUsingEncoding:
当字符串无法无损转换为指定编码时返回NULL
,从而导致崩溃。您可以使用canBeConvertedToEncoding:
确保可以进行转换。此外,值
1
对应于NSASCIIStringEncoding
,对于具有Unicode字符的字符串来说肯定会失败。NSUTF8StringEncoding
可能更合适。cStringUsingEncoding:
returnsNULL
when the string cannot be losslessly converted to the specified encoding, hence your crash. You can usecanBeConvertedToEncoding:
to ensure the conversion is possible.Furthermore, the value
1
corresponds toNSASCIIStringEncoding
which will certainly fail for a string with Unicode characters.NSUTF8StringEncoding
might be more appropriate.