views:

14

answers:

1

I'm new to iPhone dev. My app is dynamically creating buttons, following from my data model. The model isn't just a simple list; it's a tree. I need some way to correlate a created button to that data model, so that when the button is clicked I know what part of the model it corresponds to.

On Windows, most UI controls have a "tag" field where you could put custom data. Using a similar pattern, what I'd like to do on the iPhone is this:

- (void)createMyButton:(MyModel*)foo
{
  UIButton* button = <insert creation code here>
  [button addTarget:self action:@selector(handleCreatedButtonTouch:) ...];
  button.tag = foo;
}

- (void)handleCreatedButtonTouch:(id)sender
{
  UIButton* button = (UIButton*)sender;
  MyModel* foo = (MyModel*)(button.tag);
  [foo userTouchedMyButton];
}

I can't find any mention of such a field in the Apple documentation. How do you iPhone gurus do this? Again, I don't have any simple way of indexing into my data model, and doing an enumeration over the entire data model to find a match seems very wrong.

+1  A: 

Andrew,

UI elements in the iPhone SDK have a tag property similar to what you are describing. If you're looking to use button.tag, then you can do so out of the box.

The only change to your pseudo-code would be in your handleCreatedButtonTouch: method. the line:

MyModel* foo = (MyModel *)(button.tag);

would try to cast the tag property to a MyModel object. You would probably want to create an initializer in MyModel to that handles the lookup, such as:

MyModel *foo = [[MyModel alloc] initFromButtonWithTag:[sender tag]];

Hope this helps.

Neal L
This works, thanks! I looked through the documentation again and I find this under the MacOS X documentation for "NSControl" but not for the iPhone's "UIControl". What's up with that? Is the documentation off?
AndrewS
Sometimes you have to dig pretty deep into the documentation to find what you are looking for. `UIButton` inherits from `UIControl`, and `UIControl` inherits from `UIView`, and `UIView` has the `tag` property. You can visualize it as: `UIControl : UIView : UIResponder : NSObject`, where `UIView` supports `tag`.
Neal L