Using NSJSONSerialization on a returned NSData from a network call I get back a nested structure of NSDictionaries and NSArrays.
Now I wanted to parse that tree structure and prepare it for further use. Each node of the tree always carries an NSArray of sub nodes (NSDictionaries). Every one of these nodes should have a back reference to it’s parent node, containing the NSArray the sub node is part of.
This is a basic example of the structure I am talking about:
Node {
nodes:[
node {parent:Node,name:foo},
node {parent:Node,name:bar},
node {parent:Node,name:baz},
]
,name:root}
Each node is an NSDictionary and each sub nodes collection an NSArray, containing NSDictionaries.
I learned, that I cannot just add a new key “parent” and set its value to the parent node dictionary. That creates a segfault when calling the object.
Basic example of the code, creating the parent key:
NSMutableDictionary * foo = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"foo",@"name",[NSNumber numberWithInt:1],@"value",nil];
NSMutableDictionary * bar = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"bar",@"name",[NSNumber numberWithInt:2],@"value",nil];
NSMutableDictionary * baz = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"baz",@"name",[NSNumber numberWithInt:3],@"value",nil];
NSMutableArray *array = [NSMutableArray arrayWithObjects:foo,bar,baz,nil];
NSMutableDictionary * container = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"root",@"name",array,@"nodes",nil];
[foo setValue:container forKey:@"parent"];
NSLog(@"%@",foo); // <-- segfault here
Why am I getting a segmentation fault? Is this an infinite loop while printing out the description of the structure because of the back reference in the parent key of the node?
Dou you guys have any other approach to this problem here? Do I have to hold an external representaion of the tree structure, pointing to each key or IS there actually a way of storing some kind of reference to the parent node??
Many, many thanks in advance!!!
It seems to me that you can use a simple objective C class here with the interface like
I am not sure if this is the best way to do it, but you should not be using
NSDictionary. The reason why you are getting the segmentation fault is probably because of the back reference creating an infinite loop in theNSLog.EDIT: Upon googling, I found that there is a class NSTreeNode which should make things simpler for you.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSTreeNode_class/Introduction/Introduction.html