2016-07-07 35 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 

让我知道如果这能帮助你;)