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:
- 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) - Have a
NSDictionary
that associates buttons to store items. (very flexible but not very nice to maintain since you need to add aNSDictionary
to yourStoreViewController
for every association) - Custom views may have a
userInfo
dictionary. (this works well forASIHTTPRequest
, what are the downsides of using this in a view?) - ???
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: