Reputation: 5510
I would like to know if there is a way to attach a NSDictionary
object to a cell that is displayed in a UITableView
, so when a cell is selected I can access the NSDictionary
attached to that tableviewcell.
Upvotes: 3
Views: 445
Reputation: 644
You should strive to decouple the data model (NSDictionary) from the view (MyCell). That's what the view controller is for - to manage the relationship between each cell and the data.
Your data model would typically be an NSArray. Each element in the array corresponds to a row in the table (the indexPath). Each NSArray element would hold an NSDictionary object (the data model) for each cell.
Upvotes: 1
Reputation: 78393
Sure, just make a subclass of the cell and add your dictionary. You can use a completely empty implementation as well:
// MyCell.h
@interface MyCell : UITableViewCell
@property (nonatomic, strong) NSDictionary* dictionary;
@end
// MyCell.m
@implementation MyCell
@end
Now, just make sure you set your cell class if you're using a storyboard, or register it if you're not, and then just set the dictionary when you dequeue it and read it when you get the cell back later.
Upvotes: 3
Reputation: 11675
You can achieve this if you subclass a UITableViewCell
and create a NSDictionary
property in your custom cell.
Assuming you have set this property before somewhere, here's how you retrieve it when the cell is selected:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCustomCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSLog(@"%@",cell.dictionary); //replace "dictionary" by the name of the property you created in the subclass
}
Upvotes: 2