2010-07-24 69 views
13

我使用此代碼讀取SQLite數據庫的數據:iPhone stringWithCString已過時

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

但是編譯器給我的警告,在標題寫的...所以,什麼是正確的,而不是過時的方法從sqlite檢索值?

謝謝!

回答

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

我想你通常會使用NSUTF8StringEncoding,所以你的代碼看起來像

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

或者,您可以使用

keyFromSq1 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(preparedStatement, 1)]; 
+0

'[[NSString alloc] initWithBytes:bytes length:count encoding:NSUTF8StringEncoding]'更好,如果您仔細考慮Apple的文檔,請訪問https://developer.apple.com/reference/foundation/nsstring/1497290-stringwithcstring ?語言= objc – 2016-08-25 11:45:54

5

由於SQLite總是返回UTF-8 *編碼的字符串,所以you could just use +stringWithUTF8String:

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

(*或UTF-16,如果你使用sqlite3_column_text16

1

[[NSString alloc] initWithBytes:bytes length:count encoding:NSUTF8StringEncoding] 最好stringWithCString:encoding:

Apple's Document的建議是不是很確定,因爲原來的方法‘不以NULL字符短停下來。’