Monday, August 31, 2009

Nested Arrays

I'm staying the heck away from talking about Flash for a while.

In my quest for a good solution for handling table-based detail editing panes, I've been experimenting with using nested arrays to drive the table structure. A nested array is nothing more than an array of arrays (and I'm talking about NSArray instances here). The main or outer array contains one instance of NSArray for each section, and each subarray contains one object for each row in the section it represents. It takes multiple nested arrays to hold the structure of a table, with one nested array holding the labels, another holding the keys, and another holding the class of the controller class that can be used to edit that item. They're paired nested arrays, I guess.

This solution isn't quite as turnkey as the property-list driven solution I was working on earlier, but it's conceptually a lot easier to explain, and it doesn't squirrel away all the code I need to demonstrate into complex, generic classes. It's a hell of a lot better than having large nested switch statements in your controller class.

The entire process I'm developing will be shown in More iPhone 3 Development, but here's a category to make it easier to pull information out of a nested array in case you want to experiment on your own. This category adds a method to NSArray that lets you retrieve the right object from the nested array for a given NSIndexPath. Note that this category, like the table views it was created to support, supports only simple index paths that store a row and a section.

NSArray-NestedArray.h
//
// NSArray-NestedArrays.h
#import <Foundation/Foundation.h>


@interface NSArray(NestedArrays)
/*!
This method will return an object contained with an array
contained within this array. It is intended to allow
single-step retrieval of objects in the nested array
using an index path
*/

- (id)nestedObjectAtIndexPath:(NSIndexPath *)indexPath;
@end



NSArray-NestedArray.m
//
// NSArray-NestedArrays.m
#import "NSArray-NestedArrays.h"

@implementation NSArray(NestedArrays)
- (id)nestedObjectAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
NSUInteger section = [indexPath section];
NSArray *subArray = [self objectAtIndex:section];

if (![subArray isKindOfClass:[NSArray class]])
return nil;

if (row >= [subArray count])
return nil;

return [subArray objectAtIndex:row];
}

@end

No comments:

Post a Comment