我正在开发一个网络应用程序......但在通过网络发送它之前,我正在测试我的数据打包和解包......但我得到了很多垃圾值
ui 文本字段中的 myfield .. 我的标签是 uilabel ... mybutton 方法在按下按钮时被调用
在 rec 方法中,x 中的值(垃圾)从 -231231223432.... 到 +3423423423....
另外,如果我想用这些数据打包一个 nsstring,我将如何打包和解包它
enum
{
gkMessageSent,
gkMessageNotsent
};
-(void)rec:(NSData *)data
{
const char *incomingPacket = (const char *)[data bytes];
char messageType = incomingPacket[0];
switch (messageType)
{
case gkMessageSent:
{
float x = *(float *)(incomingPacket + 1 );
// value of x are not correct here
NSString *resultString = [[NSString alloc] initWithFormat:@"%f",x];
mylabel.text= resultString;
break;
}
case gkMessageNotsent:
{
mylabel.text=@"2";
break;
}
default:
mylabel.text=@"3";
break;
}
}
-(IBAction)mybutton{
float myvalue=[myfield.text floatValue];
// i check myvalue here and its fine
NSMutableData *data= [NSMutableData dataWithCapacity:1+sizeof(float)];
int myrand=1+rand()%3;
if(myrand==1)
{
char messageType = gkMessageSent;
[data appendBytes:&messageType length:1];
[data appendBytes:&myvalue length:sizeof(float)];
}
else {
char messageType = gkMessageNotsent;
[data appendBytes:&messageType length:1];
[data appendBytes:&myvalue length:sizeof(float) ];
}
[self rec:data];
}
经过一些研究,我找到了一种将 NSString 打包到 NSmutabledata 中的方法,但无法弄清楚解包
-(IBAction)mybutton {
float myvalue=300;
NSString *resultString = [[NSString alloc] initWithFormat:@"%.2f",myvalue];
NSMutableData *data=nil;
data= [NSMutableData dataWithCapacity:1+([resultString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) ];
int myrand=1+rand()%3;
if(myrand==1)
{
char messageType = gkMessageSent;
[data appendBytes:&messageType length:1];
[data appendBytes:[resultString UTF8String] length:[resultString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
}
else {
char messageType = gkMessageNotsent;
[data appendBytes:&messageType length:1];
[data appendBytes:[resultString UTF8String] length:[resultString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
}
[self rec:data];
}
-(void)rec:(NSData *)data{
const char *incomingPacket = (const char *)[data bytes];
char messageType = incomingPacket[0];
switch (messageType)
{
case gkMessageSent:
{
// Have to get the String here
break;
}
case gkMessageNotsent:
{
mylabel.text=@"2";
break;
}
default:
mylabel.text=@"3";
break;
}
}