I have a screen that shows details of a “Newspaper” (model) instance. The ViewController of my screen has one property for this Newspaper model. A Newspaper instance contains several Article instances, and these Article instances must be represented as UIButtons in the screen. Tapping the UIButton must display an alert message containing the title of the Article.
What are some good ways to associate the UIButton with an Article model?
Basically, when tapping the UIButton, how do I retrieve the UIButton’s corresponding Article instance?
I currently have two approaches in mind:
- Override the UIButton, and add a property for the Article instance.
- This violates the MVC model, since the view (UIButton) has a direct means of communication with the model (Article), but this will simplify button actions since the UIButton can simply call its property to know what Article instance will be used to do the action (display an alert message containing the title of the Article).
- Create an NSArray of UIButtons (buttonsArray), and an NSArray of Article instances (articlesArray).
- Index 0 of the buttonsArray correspond to index 0 of the articlesArray. The Article instance associated with the tapped UIButton will be based on the button’s position in the array. In order to retrieve the corresponding Article of a UIButton, the buttonsArray must be looped until the tapped UIButton is found, and then getting the Article from the articlesArray using the same index.
Are there better ways to achieve this?
EDIT: The buttons will have animations and gesture recognizers.
Also, the information needed by the button action from the Article model does not only include the title (e.g. article position, or the object itself if it will be passed to another screen, etc.).
You could use your 2nd approach, but use an NSDictionary instead of two arrays.
Or you could use your first approach but instead of adding a property for your article instance, just add a generic string property like ‘additionalTitle’ or sth. That way you don’t create a direct dependency between your button class and your model class. You could then save the title for the alertview in this property.