iOS OC,如何将RLMObject转换为NSDictionary,NSArray?

时间:2016-07-07 14:18:57

标签: ios objective-c realm

如何将RLMObject转换为NSDictionary? 这是我的代码:

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 个答案:

答案 0 :(得分:5)

我已经使用这个类解决了这个问题。与之前的答案非常相似,但在这种情况下,我为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

请告诉我这是否可以帮助您;)

答案 1 :(得分:2)

您可以使用Realm的键值编码属性轻松地将所有值提取到NSDictionary

NSMutableDictionary *headerDictionary = [NSMutableDictionary dictionary];

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

如果您需要任何其他说明,请与我们联系!