David David - 18 days ago 5
iOS Question

Using my own Cell object in XCODE

I have successfully created my on "cell" object (based on UITableViewCell) and have successfully used it while building a table via cellForRowAtIndexPath.

However, how do I deconstruct what I have done within didSelectRowAtIndexPath?

I currently receive the error "Incompatible pointer types initializing 'MyCell *__strong' with an expression of type 'UITableViewCell'"

Given my object (MyCell) is based on UITableViewCell I don't understand why I am getting this error.

Can you please help me understand what I am doing wrong.

My alternative is to use a "TAG" for each of the two labels in the cell and get them that way, but I am just experimenting here trying to learn more about how this all works.

Any help would be greatly appreciated.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"myCellID";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

if (cell == nil) {
cell = [[MyCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}

cell.accountCode.text = @"0009810";
cell.accountName.text = @"Agent Name";

return cell;
}


Here is the other method. I get the error on MyCell *cell = [tableView cellForRowAtIndexPath:indexPath];

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

// Get the cell that was selected
MyCell *cell = [tableView cellForRowAtIndexPath:indexPath];

AccountRecord *accountRecord = [[AccountRecord alloc] init];
accountRecord.accountCode = cell.accountCode.text;
accountRecord.accountName = cell.accountName.text;

[self performSegueWithIdentifier:@"AccountDetail" sender:accountRecord];

}


And here is MyCell

#import <UIKit/UIKit.h>

@interface MyCell : UITableViewCell

@property (nonatomic,strong) IBOutlet UILabel *accountCode;
@property (nonatomic,strong) IBOutlet UILabel *accountName;

@end


Any help would be appreciated.

Answer

Change this:

MyCell *cell = [tableView cellForRowAtIndexPath:indexPath];

to the following:

MyCell *cell = (MyCell *) [tableView cellForRowAtIndexPath:indexPath];