NSObject または NSObject のサブクラスの MD5 ハッシュを生成するには、簡単にハッシュ可能でありながらインスタンスの状態を表すものに変換する必要があります。JSON 文字列はそのようなオプションの 1 つです。コードは次のようになります。
Model.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];