这两个方法常常会困惑我们,它们有什么区别呢?
定义
isKindOfClass:
判断是否是这个类或者这个类的子类的实例
isMemberOfClass:
判断是否是这个类的实例
使用
关于使用,在网上看到一个很形象的例子,这里就直接拿来用了。
这里有两个类,分别是继承于NSObject的Person,Person的Teacher
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
NSString *name;
}
-(void)setName:(NSString*)n;
@end
#import "Person.h"
@implementation Person
-(void)setName:(NSString *)n
{
name = n;
}
@end
#import "Person.h"
@interface Teacher : Person
-(void)teach;
@end
#import "Teacher.h"
@implementation Teacher
-(void)teach
{
NSLog(@"我教数学");
}
@end
使用isKindOfClass的例子:
Person *person = [[Person alloc] init];
Teacher *teacher = [[Teacher alloc] init];
//YES
if ([teacher isKindOfClass:[Teacher class]]) {
NSLog(@"teacher 是 Teacher类或Teacher的子类");
}
//YES
if ([teacher isKindOfClass:[Person class]]) {
NSLog(@"teacher 是 Person类或Person的子类");
}
//YES
if ([teacher isKindOfClass:[NSObject class]]) {
NSLog(@"teacher 是 NSObject类或NSObject的子类");
}
使用isMemberOfClass的例子:
Person *person = [[Person alloc] init];
Teacher *teacher = [[Teacher alloc] init];
//YES
if ([teacher isMemberOfClass:[Teacher class]]) {
NSLog(@"teacher Teacher类的成员");
}
//NO
if ([teacher isMemberOfClass:[Person class]]) {
NSLog(@"teacher Person类的成员");
}
//NO
if ([teacher isMemberOfClass:[NSObject class]]) {
NSLog(@"teacher NSObject类的成员");
}