要为 NSObject 或 NSObject 的子类生成 MD5 哈希,您需要将其转换为易于哈希但仍代表实例状态的东西。JSON 字符串就是这样一种选择。代码如下所示:
模型.h
#import <Foundation/Foundation.h>
@interface Model : NSObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * type;
@property (nonatomic, retain) NSString * unit;
@property (nonatomic, retain) NSArray * fields;
- (NSString *)md5Hash;
@end
模型.m
#import <CommonCrypto/CommonDigest.h>
#import "Model.h"
@implementation Model
- (NSString *)md5Hash
{
// Serialize this Model instance as a JSON string
NSDictionary *map = @{ @"name": self.name, @"type": self.type,
@"unit": self.unit, @"fields": self.fields };
NSError *error = NULL;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:map
options:NSJSONWritingPrettyPrinted
error:&error];
if (error != nil) {
NSLog(@"Serialization Error: %@", error);
return nil;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Now create the MD5 hashs
const char *ptr = [jsonString UTF8String];
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
CC_MD5(ptr, strlen(ptr), md5Buffer);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x",md5Buffer[i]];
return output;
}
@end
然后您只需调用该md5Hash
方法即可轻松检索MD5哈希
Model *obj = [Model new];
obj.name = @"...";
obj.type = @"...";
obj.unit = @"...";
obj.fields = @[ ... ];
NSString *hashValue = [obj md5Hash];