title: Categories and instance variables
body: <p>I am attempting to add a category to <code>NSMutableArray</code> to allow me to use it as a 2D array (backed by the 1D array, with a method to convert x &amp; y indexes into a flat index). As I am not allowed to add instance variables to a category, how should I keep track of row and column counts which are required to calculate the index into the array?</p>
  
  <p>Here is the interface:</p>
  
  <pre><code>@interface NSMutableArray (TK2DMutableArray)
  - (id) initWithColumns:(int) columns rows:(int) rows;
  - (id) objectAtColumn:(int) col row:(int) row;
  - (void) putObject:(id) object atColumn:(int) x Row:(int) y;
  @end
  </code></pre>
  
  <p>And here is the implementation:</p>
  
  <pre><code>@implementation TK2DMutableArray
  
  - (id) initWithColumns:(int) x rows:(int) y {
      self = [self initWithCapacity:x * y];
  
      return self;
  }
  
  - (id) objectAtColumn:(int) col row:(int) row {
      return [self objectAtIndex:[self indexAtColumn:col row:row]];
  }
  
  - (void) putObject:(id) object atColumn:(int) x row:(int) y {
      [self replaceObjectAtIndex:[self indexAtColumn:x row:y] withObject:object];
  }
  
  - (int) indexAtColumn:(int) col row:(int) row {
      return (col + (row * rows));
  }
  
  @end
  </code></pre>
  
  <p>I originally coded it up as a subclass of <code>NSMutableArray</code>; I now know that was a mistake having read up a little on class clusters. The problem is right there in the last method - what should I do with <code>rows</code>? It'd be a regular old ivar if I was subclassing.</p>
  
  <p>I'm fully expecting to be told to create a new class with an <code>NSMutableArray</code> as a property, but I wanted to see if there was a way to do it with categories first.</p>
  
  <p>Many thanks.</p>