NSString to NSData using stringWithUTF8String和dataUsingEncoding返回nil

时间:2014-10-20 17:20:21

标签: objective-c cocoa nsstring nsdata

当我将NSString转换为NSData并返回时,我得到一个零结果

NSString * test = @"Wft0r3qkzXd5TDBeCahUB3MtHuc8Axwr";

NSData * testData = [test dataUsingEncoding:NSUTF8StringEncoding];

NSString * result = [NSString stringWithUTF8String:[testData bytes]];

停止

Printing description of testData:
<57667430 7233716b 7a586435 54444265 43616855 42334d74 48756338 41787772>
Printing description of result:
<nil>

3 个答案:

答案 0 :(得分:3)

我相信你正在寻找这种方法:

- (instancetype)initWithData:(NSData *)data
                    encoding:(NSStringEncoding)encoding

来自苹果医生:NSString class reference

答案 1 :(得分:3)

在Swift中,您可以看到从字符串到数据到字符串的往返,如下所示:

let srcString = "Wft0r3qkzXd5TDBeCahUB3MtHuc8Axwr"
let stringAsData = srcString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let dstString = NSString(data: stringAsData, encoding: NSUTF8StringEncoding)!
dstString // => "Wft0r3qkzXd5TDBeCahUB3MtHuc8Axwr"

基本上,您要使用NSString(data:NSData,encoding:UInt)而不是NSString(UTF8String:UnsafePointer<Int8>)

NSData是一个包装字节缓冲区的Cocoa对象。但是你使用的方法需要UnsafePointer<Int8>,换句话说,是一个原始指针,它只是一个数字内存地址,指向一个字节数组的开头。

答案 2 :(得分:0)

Swift 3

let string = "aHft0r3qkzjuh5rdsaeCahUB3MtHuc8Axwrfdvxgf"
  let stringData = string.data(using: String.Encoding.utf8, allowLossyConversion: false)!
    let finalString = NSString(data: stringData, encoding: String.Encoding.utf8.rawValue)!;