1. Daniel Tull
  2. DTFoundation

Source

DTFoundation / DTFoundation / DTTraversableDictionary.m

//
//  DTTraversableDictionary.m
//  DTKit
//
//  Created by Daniel Tull on 21/05/2009.
//  Copyright 2009 Daniel Tull. All rights reserved.
//

#import "DTTraversableDictionary.h"


@implementation DTTraversableDictionary

@synthesize currentKey;

- (void)dealloc {
	[currentKey release];
	[super dealloc];
}

- (id)objectForKey:(id)aKey {
	self.currentKey = aKey;
	return [super objectForKey:aKey];
}

- (id)firstObject {
	
	if ([self count] == 0) return nil;
	
	self.currentKey = [self.sortedKeys objectAtIndex:0];
	return [self objectForKey:self.currentKey];
}

- (id)lastObject {
	
	if ([self count] == 0) return nil;
	
	self.currentKey = [self.sortedKeys lastObject];
	return [self objectForKey:self.currentKey];
}

- (id)nextObject {
	
	if ([self count] == 0) return nil;
	
	if (!self.currentKey || ![self.sortedKeys containsObject:self.currentKey]) return [self firstObject];
	
	NSInteger currentIndex = [self.sortedKeys indexOfObject:self.currentKey];
	
	if (currentIndex == ([self count] - 1)) return nil;
	
	self.currentKey = [self.sortedKeys objectAtIndex:(currentIndex + 1)];
	return [self objectForKey:self.currentKey];
}

- (id)previousObject {
	
	if ([self count] == 0) return nil;
	
	if (!self.currentKey || ![self.sortedKeys containsObject:self.currentKey]) return [self firstObject];
	
	NSInteger currentIndex = [self.sortedKeys indexOfObject:self.currentKey];
	
	if (currentIndex == 0 || currentIndex > 1000000000) return nil; // WHY THE CHECK FOR > 100000000 ??
	
	self.currentKey = [self.sortedKeys objectAtIndex:(currentIndex - 1)];
	return [self objectForKey:self.currentKey];
}

@end