views:

60

answers:

4

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"?

+3  A: 
if ([cell isKindOfClass:[CustomCell class]]) {
    [(CustomCell*)cell customCellMethod];
}
Squeegy
+2  A: 
if ([cell isKindOfClass:[CustomCell class]]) {
   // ...
}
m5h
+1  A: 

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)].

Barry Wark
I think the use case is pretty clear in this case. Especially with the way ObjectiveC typing works. You have a table view filled with cells of various subclasses of `UITableViewCell`, and you ask for one with `[tableView cellForRowAtIndexPath:indexPath]`. That table view method only promises to return an instance of `UITableViewCell`, and the only way to know if you have a subclass of that cell is to test its class. You could create a protocol, but you would be putting most of your custom cell methods in it anyway, making things a lot more verbose for little apparent benefit.
Squeegy
A: 

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
dreamlax