Skip to content

Instantly share code, notes, and snippets.

@kballenegger
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save kballenegger/9516926 to your computer and use it in GitHub Desktop.

Select an option

Save kballenegger/9516926 to your computer and use it in GitHub Desktop.
Apple's default way of describing collections seriously blows. JSON is better.
//
// CBJSONCollectionDescriptions.m
// Chartboost
//
// Created by Kenneth Ballenegger on 3/12/14.
//
//
#import "CBJSONCollectionDescriptions.h"
#import <objc/runtime.h>
@interface NSArray (CBJSONCollectionDescriptions)
- (NSString *)CBJSONCollectionDescriptions_descriptionWithLocale:(id)locale;
@end
@interface NSDictionary (CBJSONCollectionDescriptions)
- (NSString *)CBJSONCollectionDescriptions_descriptionWithLocale:(id)locale;
@end
void CBJSONCollectionDescriptionsSwizzle(void) {
// TODO: macro disables this?
Method originalD, swizzledD, originalA, swizzledA;
originalD = class_getInstanceMethod([NSDictionary class], @selector(descriptionWithLocale:));
swizzledD = class_getInstanceMethod([NSDictionary class], @selector(CBJSONCollectionDescriptions_descriptionWithLocale:));
method_exchangeImplementations(originalD, swizzledD);
originalA = class_getInstanceMethod([NSArray class], @selector(descriptionWithLocale:));
swizzledA = class_getInstanceMethod([NSArray class], @selector(CBJSONCollectionDescriptions_descriptionWithLocale:));
method_exchangeImplementations(originalA, swizzledA);
}
NSString *CBJSONCollectionDescriptionsDescriptionForObject(id, id);
NSString *CBJSONCollectionDescriptionsDescriptionForObject(id obj, id locale) {
if (![NSJSONSerialization isValidJSONObject:obj]) {
return [obj CBJSONCollectionDescriptions_descriptionWithLocale:locale];
} else {
NSData *d = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:NULL];
return [[[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding] autorelease];
}
}
@implementation NSArray (CBJSONCollectionDescriptions)
- (NSString *)CBJSONCollectionDescriptions_descriptionWithLocale:(id)locale {
return CBJSONCollectionDescriptionsDescriptionForObject(self, locale);
}
@end
@implementation NSDictionary (CBJSONCollectionDescriptions)
- (NSString *)CBJSONCollectionDescriptions_descriptionWithLocale:(id)locale {
return CBJSONCollectionDescriptionsDescriptionForObject(self, locale);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment