Goal C, how to query if an object has a specific class

I get from TableViewCell. When I query the table view for the index path, it returns a UITableViewCell. How do I know if this object is one of my custom "CustomCell" types?

+4
source share
4 answers
if ([cell isKindOfClass:[CustomCell class]]) { [(CustomCell*)cell customCellMethod]; } 
+3
source
 if ([cell isKindOfClass:[CustomCell class]]) { // ... } 
+2
source

As always in object oriented design, trying to use an instance class identifier 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, no, this is a much better design that depends on the interface (a @protocol in Objective-C) than the class, because it helps to separate the design. Define @protocol with the appropriate API that you need and your CustomCell implements this protocol. In your code, you can check:

 if([cell conformsToProtocol:@protocol(MyCellProtocol)]) { //... } 

instead of testing to identify the class.

If you need only one method, you can use [cell respondsToSelector:@selector(myMethod)] .

+1
source

There are actually two methods that you can use here. You probably need isKindOfClass: but there is another isMemberOfClass: method, and this will only return YES if the recipient is an instance of the provided class and not an instance of the subclass.

For example, if DerivedClass is a subclass of BaseClass , then the results of each method are shown here:

 BOOL isKind = [aDerivedInstance isKindOfClass:[BaseClass class]]; // YES BOOL isMember = [aDerivedInstance isMemberOfClass:[BaseClass class]]; // NO 
0
source

Source: https://habr.com/ru/post/1306332/


All Articles