Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

cocoa - How can I escape unicode characters in a NSString?

When I store a NSString inside some NSDictionary and log that dictionary to the console like this:

NSString *someString = @"Münster";  
NSDictionary *someDict = [ NSDictionary dictionaryWithObjectsAndKeys: 
    someString, @"thestring" ];
NSLog ( @"someDict: %@", [ someDict description ] );

The console output looks like this:

unicode_test[3621:903] someDict:
{
    thestring = "MU00fcnster";
}

with the string's unicode character escaped. Is there any method to convert a NSString to this escaped representation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem could be solved using a loop on a UniChar-string representation of the given string. Implemented as extension on NSString it would look something like this:

- (NSString *) escapedUnicode  
{  
    NSMutableString *uniString = [ [ NSMutableString alloc ] init ];  
    UniChar *uniBuffer = (UniChar *) malloc ( sizeof(UniChar) * [ self length ] );  
    CFRange stringRange = CFRangeMake ( 0, [ self length ] );  

    CFStringGetCharacters ( (CFStringRef)self, stringRange, uniBuffer );  

    for ( int i = 0; i < [ self length ]; i++ ) {  
        if ( uniBuffer[i] > 0x7e )  
            [ uniString appendFormat: @"\u%04x", uniBuffer[i] ];  
        else  
            [ uniString appendFormat: @"%c", uniBuffer[i] ];  
    }  

    free ( uniBuffer );  

    NSString *retString = [ NSString stringWithString: uniString ];  
    [ uniString release ];  

    return retString;  
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...