Skip to content

Instantly share code, notes, and snippets.

@maniak-dobrii
Last active August 29, 2015 13:56
Show Gist options
  • Save maniak-dobrii/9343646 to your computer and use it in GitHub Desktop.
Save maniak-dobrii/9343646 to your computer and use it in GitHub Desktop.
Unescape unicode string for debug purposes. Convert \Uabcd, \\Uabcd, \uabcd, \\uabcd to it's symbol representation (fe: "\\U002E\\U002C" to ".,"). Useful for NSLog'ing NSManagedObjects.
/*
This one may be not optimal, first solution, but helps with NSLogs.
So you can have:
NSManagedObject *object = ...
// No \\Uabcd's in log
NSLog(@"object = %@", [[object debugDescription] unicodeUnescape]);
*/
@interface NSString (Unescape)
- (NSMutableString *)unicodeUnescape;
@end
@implementation NSString (Unescape)
/**
Creates unescaped string based on reciever. Does not modify receiver.
Takes \Uabcd, \\Uabcd, \uabcd, \\uabcd, for example converts "\\U002E\\U002C" to ".,".
@note may return exact same string from self, if it's unable to create a regexp (which is
probably possible if API changes)
@return Newly created NSMutableString
*/
- (NSMutableString *)unicodeUnescape
{
NSError *error = nil;
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"(\\\\{1,2})(U|u)([0-9a-fA-F]{4})"
options:0
error:&error];
if(error)
{
NSLog(@"%s, unable to create regexp", __PRETTY_FUNCTION__);
return [self mutableCopy];
}
// replace to make characters be of \uabcd format
NSMutableString *mutableSelf = [self mutableCopy];
[regexp replaceMatchesInString:mutableSelf
options:NSMatchingReportProgress
range:NSMakeRange(0, [mutableSelf length])
withTemplate:@"\\\\u$3"];
// transform to readable representation
CFStringRef transform = CFSTR("Any-Hex/Java");
CFStringTransform((__bridge CFMutableStringRef)mutableSelf, NULL, transform, YES);
return mutableSelf;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment