0

What is the best approach for managing the association between a UIView (like a UIButton) and the model object to which they relate?

Example (made-up): Lets assume that I have a StoreViewController with this code:

- (void)viewDidLoad
{
    for(int i = 0; i < [self.storeItems count]; ++i) {
        StoreItem* item = [self.storeItems objectAtIndex:i];
        UIButton* button = [[UIButton alloc] initWithFrame:[...]];
        [button addTarget:self
                   action:@selector(itemButtonPressed:)
         forControlEvents:UIControlEventTouchDown];

        [button setTitle:item.text forState:UIControlStateNormal];

        // THIS PART!
        button.tag = i; // assuming approach 1 on the following paragraph

        [self.someView addSubView:button];
    }
    [super viewDidLoad];
}

In my event code how do I relate back to my item?

- (void)itemButtonPressed:(UIButton*)button;
{
    // THIS PART!
    StoreItem* item = [self.storeItems objectAtIndex:button.tag; // assuming approach 1

    [self addToCart:item];
}

I am already aware of some approaches:

  1. Assuming that the model is in a list (like an NSArray) set the tag attribute of the button to the same value as the object index in the list. (note: this seems to be the best option so far, but it will not work if your data is not in a list)
  2. Have a NSDictionary that associates buttons to store items. (very flexible but not very nice to maintain since you need to add a NSDictionary to your StoreViewController for every association)
  3. Custom views may have a userInfo dictionary. (this works well for ASIHTTPRequest, what are the downsides of using this in a view?)
  4. ???

Which approach do you think is the best?

What if this is a custom view and you can add fields at will? Is the userInfo approach recommended?

related:

Community
  • 1
  • 1
João Portela
  • 6,338
  • 7
  • 38
  • 51
  • Sounds like you are trying to recreate `UITableView`. Any reason why you don't want to use `UITableView`? – Paul.s Nov 24 '11 at 01:18
  • I've faced the need for this in more than one place, as such I was asking in general, but specifically in the store: the reason was appearance (specific UI needs not decided by me). – João Portela Nov 24 '11 at 10:29
  • You can do a lot of customization on a `UITableView`. Just seems like you would end up reproducing a lot of the functionality of one – Paul.s Nov 24 '11 at 10:39
  • can I display a horizontal icon list, that expands and collapses? Or maybe a product grid (for the product grid I'm adapting [this code](http://developer.apple.com/library/ios/#samplecode/ScrollViewSuite/Listings/3_Tiling_Classes_TiledScrollView_h.html#//apple_ref/doc/uid/DTS40008904-3_Tiling_Classes_TiledScrollView_h-DontLinkElementID_25) ) I would probably be very interested in doing this with a tableview, but I still think an answer to this specific question would be useful, so it's probably better to keep the question. :) – João Portela Nov 24 '11 at 16:53

0 Answers0