标签:
对象在运行时获取其类型的能力称为内省。内省可以有多种方法实现。
判断对象类型
-(BOOL) isKindOfClass: classObj判断是否是这个类或者这个类的子类的实例
-(BOOL) isMemberOfClass: classObj 判断是否是这个类的实例
我们试试这两个方法的使用。
1、新建Person类继承NSObject,新建Teacher类继承Person
1.1、新建Person类
1.#import <Foundation/Foundation.h>
2.
3.@interface Person : NSObject
4.{
5. NSString *name;
6.}
7.-(void)setName:(NSString*)n; 8.
9.@end
1.#import "Person.h"
2.
3.@implementation Person
4.-(void)setName:(NSString *)n 5.{
6. name = n;
7.}
8.
9.@end
1.2新建Teacher类
1.#import "Person.h"
2.
3.@interface Teacher : Person
4.
5.-(void)teach; 6.
7.@end
1.#import "Teacher.h"
2.
3.@implementation Teacher
4.-(void)teach 5.{
6. NSLog(@"我教数学"); 7.}
8.@end
1.3 我们先实验下isMemberOfClass方法。
1.NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2. Person *person = [[Person alloc] init];
3. Teacher *teacher = [[Teacher alloc] init];
4.
5. //YES 6. if ([teacher isMemberOfClass:[Teacher class]]) { 7. NSLog(@"teacher Teacher类的成员"); 8. }
9. //NO 10. if ([teacher isMemberOfClass:[Person class]]) { 11. NSLog(@"teacher Person类的成员"); 12. }
13. //NO 14. if ([teacher isMemberOfClass:[NSObject class]]) { 15. NSLog(@"teacher NSObject类的成员"); 16. }
17. [person release];
18. [teacher release];
19. [pool release];
打印结果:
2012-07-04 14:23:07.965 ObjectiveCTest[2460:f803] teacher Teacher类的成员
只有第一个判断打印出来,isMemberOfClass判断是否是属于这类的实例,是否跟父类有关系他不管。
1.4 isMemberOfClass方法
1.NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2.Person *person = [[Person alloc] init];
3.Teacher *teacher = [[Teacher alloc] init];
4.
5.//YES 6.if ([teacher isKindOfClass:[Teacher class]]) { 7. NSLog(@"teacher 是 Teacher类或Teacher的子类"); 8.}
9.//YES 10.if ([teacher isKindOfClass:[Person class]]) { 11. NSLog(@"teacher 是 Person类或Person的子类"); 12.}
13.//YES 14.if ([teacher isKindOfClass:[NSObject class]]) { 15. NSLog(@"teacher 是 NSObject类或NSObject的子类"); 16.}
17.[person release];
18.[teacher release];
19.[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的子类
三个结果都打印出来了。
IOS动态类型isKindOfClass, isMemberOfClass
标签:
原文地址:http://www.cnblogs.com/yuyu-2012/p/4818678.html