Reputation: 75
I'm pulling a listing of results from a SQLite3 database into a UITableView
. The code where I pull text from the database is like so:
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 though, the information is displayed properly from the char*
, but not from the 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 perfectly. However, XCode 4.2 tells me that initWithCString
has been deprecated. I know enough to understand I don't want to use deprecated code, but if initWithUTF8String
isn't working, what should I use?
Upvotes: 6
Views: 8600
Reputation: 386038
I can see that the dash in your first log line (Retrieved Cravin Chicken Sandwich ...
) isn't a simple ASCII HYPHEN-MINUS
(U+002D, UTF-8 2D). It's a Unicode EN DASH
character (U+2013, UTF-8 E2 80 93). Same for the second line. My guess is they're encoded incorrectly in your database. If you give -[NSString initWithUTF8String:]
a C-string that's not valid UTF-8, it returns nil
.
Try printing a hex dump of menuNameChars
. You can do that by setting a breakpoint on the line after the call to sqlite3_column_text
. When the breakpoint is reached, right-click/control-click menuNameChars
in your stack frame window and choose View memory of "*menuNameChars"
(note the *
).
Upvotes: 4
Reputation: 127
If you look closely at Apple Developer it seems that instance method initWithCString: is only deprecated for the version without explicit encoding: specifier. With good reason one could argue and thus perfectly valid for const char * C-string conversion to NSString. Please compare:
https://developer.apple.com/documentation/foundation/nsstring/1497394-initwithcstring
to newer initWithCString:encoding:
https://developer.apple.com/documentation/foundation/nsstring/1411950-initwithcstring?language=objc
This Foundation API change was made since macOS 10.4+.
Upvotes: 0
Reputation: 237110
It would appear the data is not encoded as UTF-8. You should find out what encoding is being used and then use initWithCString:encoding:
and pass the correct encoding.
Upvotes: 2