0

Programmers...

I have question on string constant for iOS programming.

Is it good practice to use string constant as hex values using this functions?

+ (NSString *) stringFromHex:(NSString *)str
{
    NSMutableData *stringData = [[[NSMutableData alloc] init] autorelease];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [str length] / 2; i++) {
        byte_chars[0] = [str characterAtIndex:i*2];
        byte_chars[1] = [str characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [stringData appendBytes:&whole_byte length:1];
    }

    return [[[NSString alloc] initWithData:stringData encoding:NSASCIIStringEncoding] autorelease];
}

+ (NSString *) stringToHex:(NSString *)str
{
    NSUInteger len = [str length];
    unichar *chars = malloc(len * sizeof(unichar));
    [str getCharacters:chars];

    NSMutableString *hexString = [[NSMutableString alloc] init];

    for(NSUInteger i = 0; i < len; i++ )
    {
        [hexString appendString:[NSString stringWithFormat:@"%x", chars[i]]];
    }
    free(chars);

    return [hexString autorelease];
}

So Just define only hex values in constants.h file. And simply access via using above functions for conversion rather than defining NSString variable in both files (.h and .m) like that:

// #define KAPIURL 0xadff12233434223435345354 // http://apiurl.xxx

will it take time for conversion during run time so it's not good?

Jasper
  • 7,031
  • 3
  • 35
  • 43
SamSol
  • 2,885
  • 6
  • 37
  • 56

2 Answers2

0

I don't see why you are using strtol() which is used to parse strings into integer values. If you have the string data then it's simply a question of formatting the hex characters from that data:

+ (NSString *) stringFromHex:(NSString *)str 
{   
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableString *hexString = [[[NSMutableString alloc] init] autorelease];
    const uint8_t *bytes = [data bytes];
    const NSUInteger length = [data length];
    for (NSUInteger i = 0; i < length; i++)
        [hexString appendString:[NSString stringWithFormat:@"%02x", bytes[i]]];
    return hexString;
}

Note: this method should be called hexStringFromString.

Droppy
  • 9,691
  • 1
  • 20
  • 27
0

Good practice? No.

The only thing that your code does, is making itself unreadable for some reason. I can't see the point why you would even use strings encoded in some sort of hexadecimal code. Premature optimization? An attempt of security increase through obscurity? I can't really see the reason here.

Instead of using #define for strings, use normal string constants (see Constants in Objective-C).

Note that most "good practices" are there to make your code more readable and easy to maintain. The further you are from readable code, the further you are from good practices.

Community
  • 1
  • 1
Sulthan
  • 128,090
  • 22
  • 218
  • 270