我正在从TCP/IP流中读取数据,并成功从预先存在的服务器接收字节数组.我现在正试图找到一种方法将该数组转换为NSString
.我找到了几个例子,但很难得到我想要的结果.
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]; //BYTE ARRAY OBTAINED OK!! /////////////////////////////////////////////////////// //METHOD #1 - Yields 'nil' NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; /////////////////////////////////////////////////////// //METHOD #2 - Log prints OK, but messageString says //'invalid' in debugger, and get warnings all over the //place. I know this is wrong, but it semi-works :) size_t length=[data length]; unsigned char aBuffer[length]; [data getBytes:aBuffer length:length]; aBuffer[length - 1]=0; NSString *messageString =aBuffer; NSLog (@"%s",messageString); /////////////////////////////////////////////////////// }else{ NSLog(@"No Buffer"); }
请帮忙!所提供的任何帮助都非常感谢.
我得到了答案.
我不得不改变这个:
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
对此:
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];