问题描述
我试图将一个字节数组转换为 NSString
对象。为了测试的目的,我只是试图打印出字符串的内容到日志。
I am trying to convert a byte array into a NSString
object. For testing purposes I am then just trying to print out the contents of the string to the log.
这是我得到的:
UInt8 buf[BUFSIZE];
CFIndex bytesRead = CFReadStreamRead(stream, buf, BUFSIZE);
if (bytesRead > 0) {
NSString *serverText = [[NSString alloc] initWithBytes:buf
length:(NSUInteger)BUFSIZE
encoding:NSASCIIStringEncoding];
NSLog("%@",serverText);
[serverText release];
我试图初始化一个新的 NSString
使用 initWithBytes
并将其存储在 serverText
中。我可以在调试器中看到 serverText
的值是无效地址。我对objective-c是新的,但我认为 initWithBytes
工厂方法不成功。
I am trying to initialize a new NSString
using initWithBytes
and store this in serverText
. I can see in the debugger that the value of serverText
is "invalid address". I am new to objective-c but I assume that means the initWithBytes
factory method was not successful.
包含数据。有人可以帮我吗?
The buffer contains data. Can someone help me out?
谢谢..
推荐答案
我想出了什么:
NSData *data = [[NSMutableData alloc] init];
uint8_t buffer[1024];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buffer maxLength:1024];
if(len > 0)
{
[data appendBytes:&buffer length:len];
}
NSString *serverText = [[NSString alloc]
initWithData:data
encoding:NSASCIIStringEncoding];
NSLog(@"%@", serverText);
这篇关于Objective-C - 如何将字节数组转换为NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!