isKindOfClass, isMemberOfClass的区别

这两个方法常常会困惑我们,它们有什么区别呢?

定义

首先,我们来看看它们的定义。

isKindOfClass: 

官方解释:Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class.

isMemberOfClass: 

官方解释:Returns a Boolean value that indicates whether the receiver is an instance of a given class.

使用

关于使用,在网上看到一个很形象的例子,这里就直接拿来用了。

这里有两个类,分别是继承于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的例子:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
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的子类");  
}  
[person release];  
[teacher release];  
[pool release];
输出结果:
2012-07-04 14:34:17.315 ObjectiveCTest[2595:f803] teacherTeacher类或Teacher的子类

2012-07-04 14:34:17.316 ObjectiveCTest[2595:f803] teacherPerson类或Person的子类

2012-07-04 14:34:17.316 ObjectiveCTest[2595:f803] teacherNSObject类或NSObject的子类

使用isMemberOfClass的例子: 
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
   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类的成员");  
   }  
   [person release];  
   [teacher release];  
   [pool release];

输出结果: 
2012-07-04 14:23:07.965 ObjectiveCTest[2460:f803] teacher Teacher类的成员

看了这两个例子,应该就会明白了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值