Reputation: 7164
I am trying to implement the following method in Objective-C:
- (NSString*) getGuidWithCid: (int) cid;
This method must retrieve a GUID from a database using a C++ API and then convert this GUID into a string representation of the GUID. The structure GUID returned by the C++ API has the following definition:
typedef struct _GUID {
ul_u_long Data1;
ul_u_short Data2;
ul_u_short Data3;
ul_byte Data4[ 8 ];
} GUID;
Here is my attempt to implement this method:
- (NSString*) getGuidWithCid: (int) cid
{
GUID ulguid;
((ULResultSet *) ulresultset)->GetGuid([cname UTF8String], &ulguid);
NSString* data4 = [[[NSString alloc] initWithBytes:ulguid.Data4
length:8
encoding: NSUTF8StringEncoding] autorelease];
return [NSString stringWithFormat:@"%u-%uh-%uh-%@",
ulguid.Data1,
ulguid.Data2,
ulguid.Data3,
data4];
}
The first two lines of this method are working fine, so the variable ulguid contains a valid guid. The problem I am having is with the conversion of the byte array portion of the GUID (ie. Data4 in the GUID structure). What I am getting back from this method currently is three numeric values separated by hyphens, so Data1, Data2 and Data3 seem to be represented correctly, but NULL is being shown for Data4. What am I doing wrong here?
Upvotes: 1
Views: 914
Reputation: 7164
I have successfully implemented this method as follows:
- (NSString*) getGuidWithCid: (int) cid
{
GUID ulguid;
((ULResultSet *) ulresultset)->GetGuid(cid, &ulguid);
char buffer[37];
sprintf(buffer, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
ulguid.Data1, ulguid.Data2, ulguid.Data3,
ulguid.Data4[0], ulguid.Data4[1],
ulguid.Data4[2], ulguid.Data4[3],
ulguid.Data4[4], ulguid.Data4[5],
ulguid.Data4[6], ulguid.Data4[7]);
return [[[NSString alloc] initWithBytes:buffer
length:sizeof(buffer)
encoding:NSASCIIStringEncoding] autorelease];
}
Thanks goes to Ferdinand Beyer (http://stackoverflow.com/users/34855/ferdinand-beyer) for helping me get to this solution.
Upvotes: 1
Reputation: 35925
You are calling release
on data4
immedaitely after you create it. The contents of the string, therefore, are invalid at the point you try to use it. Consider calling autorelease
instead.
Upvotes: 4
Reputation: 124997
It's possible that the bytes in ulguid.Data4 don't form a valid UTF8 string, so you get nil back when you try to create a string with those bytes.
Upvotes: 2