[英]iOS OC,How to convert RLMObject to NSDictionary,NSArray?
How to convert RLMObject
to NSDictionary
? 怎么把
RLMObject
转换成NSDictionary
? This is my code: 这是我的代码:
NSString *imei = [Utils getUUID];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"imei = %@",imei];
RLMResults<RLMRequestHeaderModel *> *models = [RLMRequestHeaderModel objectsWithPredicate:pred];
RLMRequestHeaderModel *header = models.firstObject;
// NSDictionary *headerDict = ...
return headerDict;
I have solved this problem using this class. 我已经使用此类解决了这个问题。 Very similar to the previous answer but in this case I added a special treatment for RLMArray objects or internal RLMObjects
与先前的答案非常相似,但是在这种情况下,我为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
Let me know if this can help you ;) 让我知道这是否可以帮助您;)
You can use the key-value coding properties of Realm to extract all of the values to an NSDictionary
pretty easily: 您可以使用Realm的键值编码属性轻松将所有值提取到
NSDictionary
:
NSMutableDictionary *headerDictionary = [NSMutableDictionary dictionary];
RLMSchema *schema = header.objectSchema;
for (RLMProperty *property in schema.properties) {
headerDictionary[property.name] = header[property.name];
}
Let me know if you need any additional clarification! 让我知道您是否需要任何其他说明!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.