I am deriving from TableViewCell. When i query the table view about an index path it returns a UITableViewCell. How do i find if this object is one of my custom type "CustomCell"?
if ([cell isKindOfClass:[CustomCell class]]) {
[(CustomCell*)cell customCellMethod];
}
As always in object-oriented design, trying to use an instance's class identity is a code smell and should raise a flag. What exactly are you trying to do with your custom cell? Perhaps someone can suggest a better approach.
No mater what, it's much better design to depend on an interface (a @protocol
in Objective-C speak) than a class as it helps to decouple your design. Define a @protocol
with the relevant API you need and have your CustomCell
implement that protocol. In your code you can then test:
if([cell conformsToProtocol:@protocol(MyCellProtocol)]) {
//...
}
rather than testing for class identity.
If you only need a single method, you can use [cell respondsToSelector:@selector(myMethod)]
.
There are actually two methods you could use here. The one you probably want is isKindOfClass:
, but there is another method called isMemberOfClass:
and this will only return YES
if the receiver is an instance of the provided class, not an instance of a subclass.
For example, if DerivedClass
is a subclass of BaseClass
, then here are the outcomes of each method:
BOOL isKind = [aDerivedInstance isKindOfClass:[BaseClass class]]; // YES
BOOL isMember = [aDerivedInstance isMemberOfClass:[BaseClass class]]; // NO