Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between iskindofclass and ismemberofclass [duplicate]

What is the difference between the isKind(of aClass: AnyClass) and the isMember(of aClass: AnyClass) functions in Swift?

Original Question in Objective-C

What is the difference between the isKindOfClass:(Class)aClass and the isMemberOfClass:(Class)aClass functions? I know it is something small like, one is global while the other is an exact class match but I need someone to specify which is which please.

like image 242
NoodleOfDeath Avatar asked Sep 06 '10 19:09

NoodleOfDeath


3 Answers

isKindOfClass: returns YES if the receiver is an instance of the specified class or an instance of any class that inherits from the specified class.

isMemberOfClass: returns YES if, and only if, the receiver is an instance of the specified class.

Most of the time you want to use isKindOfClass: to ensure that your code also works with subclasses.

The NSObject Protocol Reference talks a little more about these methods.

like image 65
Sebastian Celis Avatar answered Oct 18 '22 06:10

Sebastian Celis


  • isKindOfClass: indicates whether an object inherits from a given class
  • isMemberOfClass: indicates whether an object is an instance of a given class.

[[NSMutableData data] isKindOfClass:[NSData class]]; // YES
[[NSMutableData data] isMemberOfClass:[NSData class]]; // NO
like image 34
jtbandes Avatar answered Oct 18 '22 06:10

jtbandes


Suppose

@interface A : NSObject 
@end

@interface B : A
@end

...

id b = [[B alloc] init];

then

[b isKindOfClass:[A class]] == YES;
[b isMemberOfClass:[A class]] == NO;

Basically, -isMemberOfClass: is true if the instance is exactly of the specified class, while -isKindOfClass: is true if the instance is exactly of the specified class or if one of the instance's ancestors is of the specified class.

-isMemberOfClass: is seldom used.

like image 26
kennytm Avatar answered Oct 18 '22 04:10

kennytm