objective-cnsstringcloudkitnsstringencoding

How to format string encoded with NSASCIIStringEncoding


In my Objective-C project, I'm fetching a key from cloudKit and wanted to format it before like this and wondering what's wrong with the formatting,

    [cloudKitDB performQuery:query inZoneWithID:nil completionHandler:^(NSArray<CKRecord *> * _Nullable results, NSError * _Nullable error) {

    NSString *key = [[NSString alloc] initWithData:[results.firstObject objectForKey:@"keyvalue"] encoding:NSASCIIStringEncoding];
    NSLog(@"First Key Output: %@",key);
    NSLog(@"Second Key Output: %@",key);

    NSString *formattedKey = [NSString stringWithFormat:@"%@%@",[key stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]], @"1234"];
    NSLog(@"Formatted Key: %@",formattedKey);

And here my logged

2020-08-15 21:08:14.704650+0700 myapp[2208:79554] First Key Output: ADEvXp2F2BFJ2E4Lm2dSnYvHENhkFrK8
2020-08-15 21:08:14.704828+0700 myapp[2208:79554] Second Key Output: ADEvXp2F2BFJ2E4Lm2dSnYvHENhkFrK8
2020-08-15 21:08:14.705456+0700 myapp[2208:79554] Formatted Key: ADEvXp2F2BFJ2E4Lm2dSnYvHENhkFrK8

Although, I have tried to trim whitespace but still no luck!

Thanks


Solution

  • This is a strange problem, but I can reproduce it with the code below.

    Based on this I still suspect that there are some funnies behind the string and have given ways to fix it in the code.

            // Note C strlen will stop at the first 0
            char     * s            = "3Lm9dGmeTf3Lm9dGmeTf3Lm9dGmeTfdd\0\0\0";
            NSData   * data         = [NSData dataWithBytes:s length:strlen( s ) + 2];
            NSString * key          = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
            NSString * keyFormatted = [NSString stringWithFormat:@"%@%@", key, @"1234"];
    
            NSLog ( @"Key          : %@", key );
            NSLog ( @"Formatted key: %@", keyFormatted );
    
            // Use strlen to get rid of funnies
            NSData   * dataFixed = [data subdataWithRange:NSMakeRange( 0, strlen( s ) )];
            NSString * keyFixed  = [[NSString alloc] initWithData:dataFixed encoding:NSASCIIStringEncoding];
            NSString * keyForm2  = [NSString stringWithFormat:@"%@%@", keyFixed, @"1234"];
    
            NSLog ( @"Fixed key    : %@", keyFixed );
            NSLog ( @"Formatted key: %@", keyForm2 );
    
            // Use C isprint to trim ... crude but works
            while ( key.length && ! isprint ( [key characterAtIndex:key.length - 1] ) )
            {
                key = [key substringToIndex:key.length - 1];
            }
    
            keyFormatted = [NSString stringWithFormat:@"%@%@", key, @"1234"];
    
            NSLog ( @"Key          : %@", key );
            NSLog ( @"Formatted key: %@", keyFormatted );