我在NSData类别中有NSData到NSString的转换,因为我总是使用NSString方法:initWithData:encoding:。但是,根据这个答案,https://stackoverflow.com/a/2467856/1231948,并不是那么简单。
到目前为止,我的NSData类别中有这个方法,以便与其他数据对象中的方法保持一致,这些方法从同名的方法返回字符串:
- (NSString *) stringValue
{
return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
}到目前为止,它是成功的,但我想确定字符串是否为空终止,以决定是否应该使用此方法,也可以从答案链接:
NSString* str = [NSString stringWithUTF8String:[data bytes]];如何确定UTF-8编码的NSData是否包含以空结尾的字符串?
在得到下面的答案之后,我为我的NSData分类方法stringValue编写了更彻底的实现
- (NSString *) stringValue
{
//Determine if string is null-terminated
char lastByte;
[self getBytes:&lastByte range:NSMakeRange([self length]-1, 1)];
NSString *str;
if (lastByte == 0x0) {
//string is null-terminated
str = [NSString stringWithUTF8String:[self bytes]];
} else {
//string is not null-terminated
str = [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
}
return str;
}发布于 2015-01-14 03:25:49
Null终止实际上意味着最后一个字节的值为零。很容易查到:
char lastByte;
[myNSData getBytes:&lastByte range:NSMakeRange([myNSData length]-1, 1)];
if (lastByte == 0x0) {
// string is null terminated
} else {
// string is not null terminated
}发布于 2015-01-14 03:19:24
因此,您希望确定NSData的最后一个字节是否为null,您知道如何获得指向所有字节(bytes)的指针,以及有多少字节(length)。
在C中,“指向所有字节的指针”可以用作数组和索引,因此可以使用以下方法获得最后一个字节:
Byte *theBytes = data.bytes;
Byte lastByte = theBytes[bytes.length - 1];如果您需要支持以空结尾的字符串更短,那么需要扫描整个缓冲区,记住在末尾停止(所以不要使用类似strlen的东西)。
在检查null时,您将得到指向字节和长度的指针,因为您可能希望使用initWithBytes:length:encoding:来构造NSString,而不是问题中的这两个方法之一。
HTH
https://stackoverflow.com/questions/27935054
复制相似问题