I am Working on a Network application ... but before sending it over the network i am testing my packing and unpacking of data ... but i am getting a lot of garbage values
myfield in a ui text field .. my label is a uilabel ... mybutton method is called when a button is pressed
in the rec method the value(garbage) in x varies from -231231223432.... to +3423423423.....
also if i could like to pack a nsstring with this data how will i pack and unpack it
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];
}
After Some Research I found a way to pack an NSString into NSmutabledata but cant figure out the unpacking
-(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;
}
}