Correct way to convert char * to NSString without initWithCString?

I am compiling a list of results from a SQLite3 database in a UITableView . The code in which I am extracting text from the database looks like this:

 char *menuNameChars = (char *) sqlite3_column_text(statement, 1); NSString *menuName = [[NSString alloc] initWithUTF8String:menuNameChars]; NSLog(@"Retrieved %s,%@ from DB.", menuNameChars, menuName); 

When I use initWithUTF8String , sometimes the information is copied properly from the database. Sometimes, however, information is displayed correctly from char* , but not from NSString :

 2011-10-24 22:26:54.325 [23974:207] Retrieved Cravin Chicken Sandwich – Crispy, (null) from DB. 2011-10-24 22:26:54.327 [23974:207] Retrieved Cravin Chicken Sandwich – Roast, (null) from DB. 2011-10-24 22:26:54.331 [23974:207] Retrieved Jr Chicken Sandwich, Jr Chicken Sandwich from DB. 2011-10-24 22:26:54.337 [23974:207] Retrieved Prime-Cut Chicken Tenders - 3 Piece, Prime-Cut Chicken Tenders - 3 Piece from DB. 

Now, if I replace initWithUTF8String with initWithCString , the code works fine. However, Xcode 4.2 tells me that initWithCString deprecated. I know enough to understand that I do not want to use legacy code, but if initWithUTF8String does not work, what should I use?

+6
source share
3 answers

(edited)

I see that the dash in your first line of the magazine ( Retrieved Cravin Chicken Sandwich ... ) is not a simple ASCII HYPHEN-MINUS (U + 002D, UTF-8 2D). This is the Unicode EN DASH character (U + 2013, UTF-8 E2 80 93). The same goes for the second line. I assume they are incorrectly encoded in your database. If you give -[NSString initWithUTF8String:] C-string that is not valid UTF-8, it returns nil .

Try printing a hex dump of menuNameChars . This can be done by setting a breakpoint on the line after calling sqlite3_column_text . When the breakpoint is reached, right-click / control -click menuNameChars in the stack frame window and select View memory of "*menuNameChars" (note * ).

+4
source

It seems that the data is not encoded as UTF-8. You should find out what encoding is used, then use initWithCString:encoding: and pass the correct encoding.

+2
source

try the power of stringWithFormat:

+2
source

Source: https://habr.com/ru/post/900007/


All Articles