两者都是NSObject用于比较Class的方法
不同点在于:
1、isKindOfClass可用于判断对象是否是一个类的成员,或者是该派生类的成员
2、isMemberOfClass可用于判断对象是否是当前类的成员
上个🌰
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@end
@interface Men : Person
@end
Person.m
#import "Person.h"
@implementation Person
@end
@implementation Men
@end
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *person = [[Person alloc] init];
Men *man = [[Men alloc] init];
if ([person isKindOfClass:[Person class]]) {
NSLog(@"person isKindOfClass: Person");
} else {
NSLog(@"person is't kind of Person");
}
if ([man isKindOfClass:[Person class]]) {
NSLog(@"man isKindOfClass: Person");
} else {
NSLog(@"man is't kind of Person");
}
//////////////////////////////////////////////////////////////////
if ([person isMemberOfClass:[Person class]]) {
NSLog(@"person isMemberOfClass: Person");
} else {
NSLog(@"person is't member of Person");
}
if ([man isMemberOfClass:[Person class]]) {
NSLog(@"man isMemberOfClass: Person");
} else {
NSLog(@"man is't member of Person");
}
}
@end
特殊情况
NSArray *myArr = [[NSArray alloc] init];
NSMutableArray *myArr2 = [[NSMutableArray alloc] init];
if ([myArr isKindOfClass:[NSArray class]]) {
NSLog(@"myArr isKindOfClass of NSArray");
}
if ([myArr isMemberOfClass:[NSArray class]]) {
NSLog(@"myArr isMemberOfClass of NSArray");
}
if ([myArr2 isKindOfClass:[NSMutableArray class]]) {
NSLog(@"myArr2 isKindOfClass of NSMutableArray");
}
if ([myArr2 isMemberOfClass:[NSMutableArray class]]) {
NSLog(@"myArr2 isMemberOfClass of NSMutableArray");
}
NSArray、NSMutableArray属于类簇,使用isMemberOfClass不能得到正确的结果
原因:由于类簇的性质,这类对象实际返回的实例有不确定性
NSArray对象可能会在运行时发现其实运作的是NSCFArray(来自Core Foundation框架(C语言的实现版本),很多Cocoa对象都是如此做桥接的)
对于类簇的判断要谨慎