13

I use this code to read data from sqlite database:

keyFromSql = [NSString stringWithCString:(char *)sqlite3_column_text(preparedStatement, 1)];

but the compiler give me the warning wrote in the title... so, what is the right and not deprecated method to retrieve a value from sqlite?

thanks!

ghiboz
  • 7,863
  • 21
  • 85
  • 131

3 Answers3

26
+(id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc

I think you'll typically use NSUTF8StringEncoding, so your code would look like

keyFromSq1 = [NSString stringWithCString:(char *)sqlite3_column_text(preparedStatement, 1) encoding:NSUTF8StringEncoding];

Alternatively you can use

keyFromSq1 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(preparedStatement, 1)];
Austen Green
  • 504
  • 3
  • 6
  • `[[NSString alloc] initWithBytes:bytes length:count encoding:NSUTF8StringEncoding]` is better, if you think carefully about Apple's document at https://developer.apple.com/reference/foundation/nsstring/1497290-stringwithcstring?language=objc – DawnSong Aug 25 '16 at 11:45
5

Since SQLite always return UTF-8* encoded strings, you could just use +stringWithUTF8String:.

const char* res = (const char*)sqlite3_column_text(preparedStatement, 1);
keyFromSql = [NSString stringWithUTF8String:res];

(* or UTF-16, if you use sqlite3_column_text16)

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
1

[[NSString alloc] initWithBytes:bytes length:count encoding:NSUTF8StringEncoding] is preferred to stringWithCString:encoding:

Apple's Document's recommendation is not very OK, because the original method "doesn’t stop short at a NULL character."

DawnSong
  • 4,752
  • 2
  • 38
  • 38