Skip to content

Instantly share code, notes, and snippets.

@djfumberger
Created September 6, 2014 05:34
Show Gist options
  • Save djfumberger/45c60403b61342f7347f to your computer and use it in GitHub Desktop.
Save djfumberger/45c60403b61342f7347f to your computer and use it in GitHub Desktop.
+ (NSString *)hashForObject:(id)object usingMethod:(AJCHasherMethod)method {
//object = [object copy];
CC_MD5_CTX context;
CC_MD5_Init(&context);
if ([object respondsToSelector:@selector(countByEnumeratingWithState:objects:count:)]) {
if([object isKindOfClass:[NSDictionary class]]) {
// It's an NSDictionary, need to hash the keys and values seperately, combine them, then reorder them into an array.
NSMutableArray *newArray = [NSMutableArray new];
for (id subObject in [object sortedArrayUsingSelector:@selector(compare:)) {
NSString *hashedKey = [self hashForObject:subObject usingMethod:method];
CC_MD5_Update ( hashedKey );
NSString *hashedObject = [self hashForObject:object[subObject] usingMethod:method];
CC_MD5_Update ( hashedObject );
}
}
if([object isKindOfClass:[NSOrderedSet class]]) {
// Make this NSSet into an array.
object = [object array];
}
if([object isKindOfClass:[NSArray class]]) {
for (id subObject in object) {
CC_MD5_Update ( [self hashForObject:subObject usingMethod:method] );
}
} else if([object isKindOfClass:[NSSet class]]) {
for (id subObject in [object sortedArrayUsingSelector:@selector(compare:)) {
CC_MD5_Update ( [self hashForObject:subObject usingMethod:method] );
}
}
} else if ([object isKindOfClass: [NSString class]]) {
CC_MD5_Update ( string contents );
} else {
// Unknow object, used keyed archiver to hash ?
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object];
CC_MD5_Update ( data );
}
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5_Final(result, &context);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < 15; i++) {
[output appendFormat:@"%02x", result[i]];
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment