Friday, February 24, 2012

how to encode a UInt32 scalar type into a NSData object


I am currently creating this NSData object. I would like to put in sever different objects that are of type NSString and UInt32. I know how to put a NSString into my NSData object, but I don't know how to do this with a UInt32 scalar type.



this is how I do it with a NSString




- (void) constructRequest
{
NSString *mystring = [[NSString alloc] initWithString:[self addMethodName]];
UInt32 protocolInt = [self addProtocolVersion];

NSData* data=[mystring dataUsingEncoding:NSUTF8StringEncoding];
[data writeToFile:@"/Users/imac/Desktop/_dataDump.dat" atomically:YES];

}

2 comments:

  1. So I have figured it out, and instead of just updating my question I will put in the answer so others can see that this question has been answered if they are looking to do something similar.

    code is as follows

    - (void) constructRequest
    {
    //NSString *mystring = [[NSString alloc] initWithString:[self addMethodName]];
    UInt32 protocolInt = [self addProt];

    NSData * data = [[NSData alloc] initWithBytes:&protocolInt length:sizeof(protocolInt)];

    //NSData* data=[mystring dataUsingEncoding:NSUTF8StringEncoding];
    [data writeToFile:@"/Users/imac/Desktop/_dataDump.dat" atomically:YES];

    }

    ReplyDelete
  2. Does it need to be NSData? You could use NSString or NSNumber (both can be saved in a property list).

    Your scheme doesn't really distinguish between a 4-byte string and a UInt32, if that matters.

    ReplyDelete