2016-07-07 52 views
1

如何轉換RLMObjectNSDictionary? 這是我的代碼:iOS OC,如何將RLMObject轉換爲NSDictionary,NSArray?

NSString *imei = [Utils getUUID]; 

NSPredicate *pred = [NSPredicate predicateWithFormat:@"imei = %@",imei]; 

RLMResults<RLMRequestHeaderModel *> *models = [RLMRequestHeaderModel objectsWithPredicate:pred]; 

RLMRequestHeaderModel *header = models.firstObject; 

// NSDictionary *headerDict = ... 

return headerDict; 

回答

2

您可以使用鍵 - 值編碼領域的屬性所有值提取到一個NSDictionary很容易:

NSMutableDictionary *headerDictionary = [NSMutableDictionary dictionary]; 

RLMSchema *schema = header.objectSchema; 
for (RLMProperty *property in schema.properties) { 
    headerDictionary[property.name] = header[property.name]; 
} 

讓我知道如果你需要任何額外的澄清!

4

我已經使用這個類解決了這個問題。非常類似於以前的答案,但在這種情況下,我加入了特殊處理RLMArray對象或內部RLMObjects

@implementation RLMObject (NSDictionary) 

- (NSDictionary*) dictionaryRepresentation{ 
    NSMutableDictionary *headerDictionary = [NSMutableDictionary dictionary]; 
    RLMObjectSchema *schema = self.objectSchema; 
    for (RLMProperty *property in schema.properties) { 
     if([self[property.name] isKindOfClass:[RLMArray class]]){ 
      NSMutableArray *arrayObjects = [[NSMutableArray alloc] init]; 
      RLMArray *currentArray = self[property.name]; 
      NSInteger numElements = [currentArray count]; 
      for(int i = 0; i<numElements; i++){ 
       [arrayObjects addObject:[[currentArray objectAtIndex:i] dictionaryRepresentation]]; 
      } 
      headerDictionary[property.name] = arrayObjects; 
     }else if([self[property.name] isKindOfClass:[RLMObject class]]){ 
      RLMObject *currentElement = self[property.name]; 
      headerDictionary[property.name] = [currentElement dictionaryRepresentation]; 
     }else{ 
      headerDictionary[property.name] = self[property.name]; 
     } 

    } 
    return headerDictionary; 
} 

@end 

讓我知道如果這能幫助你;)