I\'m figuring out the right mechanism to pass data from UITableViewCell
s to a UIableViewController
(or UIViewController
).
Sear
Why not just use [UITableView indexPathForCell:]
with a delegate?
MyViewController.h
@interface MyViewController : UITableViewController <MyTableViewCellDelegate>
@end
MyViewController.m
@implementation MyViewController
// methods...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *reuseIdentifier = @"MyCell";
MyTableViewCell *cell = (id)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (cell == nil)
cell = [[[MyTableViewCell alloc] initWithMyArgument:someArgument reuseIdentifier:reuseIdentifier] autorelease];
[cell setDelegate:self];
// update the cell with your data
return cell;
}
- (void)myDelegateMethodWithCell:(MyTableViewCell *)cell {
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
// update model
}
@end
MyTableViewCell.h
@protocol MyTableViewCellDelegate;
@interface MyTableViewCell : UITableViewCell
@property (assign, nonatomic) id <MyTableViewCellDelegate> delegate;
- (id)initWithMyArgument:(id)someArgument reuseIdentifier:(NSString *)reuseIdentifier;
@end
@protocol MyTableViewCellDelegate <NSObject>
@optional
- (void)myDelegateMethodWithCell:(MyTableViewCell *)cell;
@end
MyTableViewCell.m
@implementation MyTableViewCell
@synthesize delegate = _delegate;
- (id)initWithMyArgument:(id)someArgument reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
if (self) {
// custom setup
}
return self;
}
- (void)prepareForReuse {
[super prepareForReuse];
self.delegate = nil;
}
- (void)someActionHappened {
if ([self.delegate respondsToSelector:@selector(myDelegateMethodWithCell:)])
[self.delegate myDelegateMethodWithCell:self];
}
@end