这两个方法常常会困惑我们,它们有什么区别呢?
定义
首先,我们来看看它们的定义。
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] teacher 是 Teacher类或Teacher的子类 2012-07-04 14:34:17.316 ObjectiveCTest[2595:f803] teacher 是 Person类或Person的子类 2012-07-04 14:34:17.316 ObjectiveCTest[2595:f803] teacher 是 NSObject类或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类的成员
看了这两个例子,应该就会明白了。
时间: 2024-11-08 21:00:02