Created
July 21, 2011 13:41
-
-
Save paxswill/1097207 to your computer and use it in GitHub Desktop.
JCITree, a quick tree structure in Obj-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface JCITree : NSObject { | |
@private | |
id value; | |
NSMutableArray *leaves; | |
JCITree *parent; | |
} | |
@property (retain) id value; | |
@property (retain, readonly) NSMutableArray *leaves; | |
@property (assign, readonly) JCITree *parent; | |
-(void)setValue:(id)aValue atIndex:(NSInteger)index; | |
-(id)getValueAtIndex:(NSInteger)index; | |
-(id)getValueAtIndexPath:(NSIndexPath *)indexPath; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
JCITree | |
*/ | |
@interface JCITree() | |
@property (retain, readwrite) NSMutableArray *leaves; | |
@property (assign, readwrite) JCITree *parent; | |
-(id)initWithParent:(JCITree *)parentNode; | |
@end | |
@implementation JCITree | |
@synthesize value; | |
@synthesize leaves; | |
@synthesize parent; | |
-(id)init{ | |
if((self = [self initWithParent:nil])){ | |
} | |
return self; | |
} | |
-(id)initWithParent:(JCITree *)parentNode{ | |
if((self = [super init])){ | |
self.parent = parentNode; | |
self.leaves = [NSMutableArray array]; | |
self.value = nil; | |
} | |
return self; | |
} | |
-(void)setValue:(id)aValue atIndex:(NSInteger)index{ | |
if(index > (NSInteger)[self.leaves count]){ | |
for(NSInteger i = (NSInteger)[self.leaves count]; i < index; ++i){ | |
[self.leaves addObject:[NSNull null]]; | |
} | |
} | |
if(index == (NSInteger)[self.leaves count]){ | |
JCITree *newLeaf = [[JCITree alloc] initWithParent:self]; | |
newLeaf.value = aValue; | |
}else{ | |
[[self.leaves objectAtIndex:index] setValue:aValue]; | |
} | |
} | |
-(id)getValueAtIndex:(NSInteger)index{ | |
return [[self.leaves objectAtIndex:index] value]; | |
} | |
-(id)getValueAtIndexPath:(NSIndexPath *)indexPath{ | |
if([indexPath length] == 1){ | |
return [self getValueAtIndex:[indexPath indexAtPosition:0]]; | |
}else{ | |
NSUInteger *indices = malloc(sizeof(NSUInteger) * [indexPath length]); | |
[indexPath getIndexes:indices]; | |
NSIndexPath *newIndexPath = [NSIndexPath indexPathWithIndexes:indices length:([indexPath length] - 1)]; | |
free(indices); | |
return [[self.leaves objectAtIndex:[indexPath indexAtPosition:0]] getValueAtIndexPath:newIndexPath]; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment