2013-10-10 66 views
1

MD5哈希我想生成一個MD5哈希一個NSObject:生成Objective-C的對象

@property (nonatomic, retain) NSString * name; 
@property (nonatomic, retain) NSString * type; 
@property (nonatomic, retain) NSString * unit; 
@property (nonatomic, retain) NSArray * fields; 

什麼是這樣做的最佳方法是什麼?我見過從字典或數組中散列的例子,但不是來自整個NSObject。

+2

什麼你的目標是? – Wain

+2

[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

+1

@ H2CO3你是什麼意思的「你人」?這個問題不是重複的,因爲它是關於散列自定義對象而不是字符串或數組或字典。是的,它是相似的,但值得回答。 – Abizern

回答

5

要生成一個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]; 
+0

謝謝,這正是我正在尋找的。 – ebi

+0

有沒有辦法用嵌套對象做到這一點? 我試圖用我的對象這樣做,但他們都有對象屬性: 財產(非原子,保留)的NSString *名稱; property(nonatomic,retain)MyRelatedObject * related; – ebi

0

您可以將對象轉換成字典,如果你已經有代碼來創建哈希:

NSDictionary *dict = [myObject dictionaryWithValuesForKeys:@[@"name", @"type", @"unit", @"fields"]]; 

或者你可以在你的類實現<NSCoding>,歸檔和散列結果數據。