[英]iOS OC,How to convert RLMObject to NSDictionary,NSArray?
怎么把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;
我已經使用此類解決了這個問題。 與先前的答案非常相似,但是在這種情況下,我為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
讓我知道這是否可以幫助您;)
您可以使用Realm的鍵值編碼屬性輕松將所有值提取到NSDictionary
:
NSMutableDictionary *headerDictionary = [NSMutableDictionary dictionary];
RLMSchema *schema = header.objectSchema;
for (RLMProperty *property in schema.properties) {
headerDictionary[property.name] = header[property.name];
}
讓我知道您是否需要任何其他說明!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.