这是一种在保持对父消息的引用的同时展平字典的方法。
@interface NSDictionary(Flatten)
- (NSArray*) flattenWithParent:(id)parent;
- (NSArray*) flatten;
@end
@implementation NSDictionary(Flatten)
- (NSArray*) flattenWithParent:(id)parent
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSMutableArray *flat = [NSMutableArray arrayWithObject:dict];
if (parent != nil)
dict[@"parent"] = parent;
[self enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
if ([value isKindOfClass:[NSDictionary class]])
[flat addObjectsFromArray:[value flattenWithParent:dict]];
else
[dict setObject:value forKey:key];
}];
return flat;
}
- (NSArray*) flatten
{
return [self flattenWithParent:nil];
}
@end
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSDictionary *data = @{
@"author": @"user",
@"message":@"message",
@"response": @{
@"author": @"user2",
@"message":@"message2",
@"response": @{
@"author": @"user",
@"message":@"message3"
}
}
};
NSArray *messages = [data flatten];
NSLog(@"Message count = %lu", messages.count);
NSLog(@"%@",messages);
}
return 0;
}
我得到以下(重新格式化)输出:
2013-05-11 09:37:31.293 Dummy[22896:303] Message count = 3
2013-05-11 09:37:31.295 Dummy[22896:303] (
{
author = user;
message = message;
},
{
author = user2;
message = message2;
parent = {
author = user;
message = message;
};
},
{
author = user;
message = message3;
parent = {
author = user2;
message = message2;
parent = {
author = user;
message = message;
};
};
})