要生成一個MD5哈希一個NSObject或NSObject的子類,你需要將其轉換成東西是很容易哈希的,但仍表示實例的狀態。 JSON字符串就是這樣一個選項。代碼如下所示:
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
Model.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];
什麼你的目標是? – Wain
[dupe1](http://stackoverflow.com/questions/2018550/how-do-i-create-an-md5-hash-of-a-string-in-cocoa)[dupe2](HTTP://計算器的.com /問題/ 652300 /使用-MD5散列上-A-字符串中的可可)[dupe3](http://stackoverflow.com/questions/1524604/md5-algorithm-in-objective-c) dupe4(http://stackoverflow.com/questions/15947597/how-to-convert-nsstring-to-md5-hash-in-objective-c)不要你的人甚至嘗試使用谷歌或網站搜索!那會是褻瀆! – 2013-10-10 20:33:13
@ H2CO3你是什麼意思的「你人」?這個問題不是重複的,因爲它是關於散列自定義對象而不是字符串或數組或字典。是的,它是相似的,但值得回答。 – Abizern