我正在從TCP/IP流讀取數據,並且正在成功接收來自預先存在的服務器的字節數組。我現在試圖找到一種方法將該數組轉換爲NSString
。我發現了幾個例子,但我很難得到我想要的結果。如何將字節數組轉換爲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");
}
請幫忙!提供的任何援助非常感謝。
爲什麼downvotes? – Dutchie432 2011-09-14 17:45:34