Reputation: 55665
I am downcasting a UITableViewCell
to a custom subclass I have created, then assigning that to a UITableViewCell
instance. Later I need to know if the downcast has occurred. Basically I need to know if the cell is an instance of the subclass even though it is now defined as an instance of the superclass.
isKindOfClass
won't do the trick because that is only true when it is an instance of that class or an instance of a class that inherits from that class, neither of which are technically true, even though the cell actually is an instance of the class but just examining the passed in variable it's impossible to know that.
How could one assign a subclass to a regular UITableViewCell
variable and later know whether nor not it's an instance of the subclass?
UITableViewCell *cell;
CustomCellClass *customCell = (CustomCellClass *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
cell = customCell;
//...
if ([cell isKindOfClass:[CustomCellClass class]]) {
//this is never true but I need to run code here
}
return cell
Upvotes: 0
Views: 462
Reputation: 6803
If the ultimate purpose of this is to use a function that is only available in the subclass then use:
If ([cell respondsToSelector:@selector(mysubclassFunction)] { // this cell is a subclass and responds to that function }
Upvotes: 1
Reputation: 507
You can't.
Either your object IS in the inheritance tree (is an instance) of CustomCellClass
, or it's NOT. There are no in between states and there's no way to change that.
Now, it would help to show us your full code, so we can give you a better explanation, but here's a try:
Now, with inheritance, there are rules. One primary rule is that you can't 'downcast' an object. You can only 'upcast' it. If you create an NSObject, you can't cast. it into a UIView. You can, however, cast a UIView into an NSObject.
So, for your code, you can't cast cell
to be a CustomCellClass
because cell isn't starting out as a CustomCellClass. Very easy change, really!
Edit:
if tableView:cellForRowAtIndexPath:
returns a CustomCellClass
object, then the following will work. But I don't recommend thinking about it as a "downcast." It is normally just called "casting".
What you want:
CustomCellClass *cell = (CustomCellClass *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
if ([cell isKindOfClass:[CustomCellClass class]]) {
// This will be true because it was created as a CustomCellClass object.
}
return cell
Upvotes: 1