Skip to content
aroemers edited this page Apr 18, 2012 · 1 revision

Integration

Using the AATree in your project is easy. Just copy the files into a place that seems suitable in your project and you are good to go.

Usage

First create a NSComparator block, which will be used to compare the keys in the tree. For example, if we use NSNumber as a key, we could use a key comparator like this:

NSComparator keyComparator = ^NSComparisonResult(id obj1, id obj2) {
  if ([obj1 intValue] < [obj2 intValue]) return NSOrderedAscending;
  else if ([obj1 intValue] > [obj2 intValue]) return NSOrderedDescending;
  else return NSOrderedSame;
};

Now that we have a key comparator, we can create the tree:

AATree *tree = [ [AATree alloc] initWithKeyComparator:keyComparator];``

Note, only use this initializer to initialize the tree. Others won't work and are not supported.

We are now ready to use the tree as we would use an NSDictionary. For example:

for (int i=0; i<10; i++) {
  [tree setObject:[NSString stringWithFormat:@"Data%@" ,[NSNumber numberWithInt:i]] forKey:[NSNumber numberWithInt:i]];
}

Now we have filled the tree with ten objects. The fastest way to retrieve objects from the tree is through the objectForKey: method. This performs a search in O(log n) steps.

NSLog(@"Data at key 5 = %@", [tree objectForKey:[NSNumber numberWithInt:5]);

Debugging

For debugging purposes, one can call print on the tree. This will cause the tree to be printed using NSLog().

[tree print];

output:
2010-06-19 01:00:13.196 [17265:a0f]             9-Data9(1)
2010-06-19 01:00:13.196 [17265:a0f]          8-Data8(1)
2010-06-19 01:00:13.197 [17265:a0f]       7-Data7(2)
2010-06-19 01:00:13.197 [17265:a0f]          6-Data6(1)
2010-06-19 01:00:13.197 [17265:a0f]    5-Data5(2)
2010-06-19 01:00:13.198 [17265:a0f]       4-Data4(1)
2010-06-19 01:00:13.198 [17265:a0f] 3-Data3(3)
2010-06-19 01:00:13.199 [17265:a0f]       2-Data2(1)
2010-06-19 01:00:13.199 [17265:a0f]    1-Data1(2)
2010-06-19 01:00:13.199 [17265:a0f]       0-Data0(1)
Clone this wiki locally