How to pass an object in the UITableCell for use in "AccessoryButtonTapped..." method?
I'm pushing another view controller when the user selects the accessoryButton and the missing component is the ability to pass my domain object along with it.
The current hack is to set the "tag" property on the UITableCell to my object and pull this out inside the "accessoryButtonTapped" function. If only this worked :)
My first question is this - How should I pass an object when I need it in the accessoryButtonTappedForRow method?
My second question is this - If my hack did work, how can I cast out the object from the cell?
Here is my "cellForRowAtIndexPath" implementation where I set the tag property of the cell to my object
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)inde开发者_C百科xPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if ([self.myArray count] > 0) {
MyClass* obj = [self.myArray objectAtIndex: [indexPath row]];
cell.textLabel.text = @"click the accessory button for details";
cell.tag = obj;
}
//other code here to finish the implementation ...
}
And here is my "accessoryButtonTappedForRow..." implementation that returns nothing for tag when I attempted to pull it out
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
MyClass* obj = [[tableView cellForRowAtIndexPath:indexPath] tag];
}
Anything else I missed is fair game (I'm open to new ideas here)
The answer is that you shouldn't.
In the way you're trying to implement, you're using UITableCell
to store a data to be operated upon. Then, you need to maintain the consistency between what's stored in UITableCell
and what's stored in self.myArray
. In a simple program, it's no problem, but it will eventually become a mess.
Instead, just retrieve from the model (in this case, your self.myArray
) the object representing the UITableCell
directly. This way, the data always flows from myArray
(model) to UITableCell
(view), not the other way around. That makes the program easier to understand in the long run.
Concretely, in your
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
and
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
you're accessing the model in the first and you're trying to access the view in the second. Don't. Just use
MyClass* obj = [self.myArray objectAtIndex: [indexPath row]];
in both delegate methods. Or better, I would define a method
-(MyClass*) objForIndexPath:(NSIndexPath*)indexPath{
return [self.myArray objectAtIndex: [indexPath row]];
}
and use
MyClass* obj = [self objForIndexPath:indexPath];
to reduce the repetition of codes.
精彩评论