Objective-C之动态类型

浏览: 170 发布日期: 2016-10-10 分类: objective-c

对象在运行时获取其类型的能力称为内省。内省可以有多种方法实现。

判断对象类型

-(BOOL) isKindOfClass: classObj判断是否是这个类或者这个类的子类的实例
-(BOOL) isMemberOfClass: classObj 判断是否是这个类的实例

新建Person和Teacher类

Person

//
//  Person.h
//  DynamicType
//
//  Created by Michael on 2016/9/27.
//  Copyright © 2016年 Michael. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject {
    NSString *name;
}

-(void) setName:(NSString*) n;

@end

//
//  Person.m
//  DynamicType
//
//  Created by Michael on 2016/9/27.
//  Copyright © 2016年 Michael. All rights reserved.
//

#import "Person.h"

@implementation Person

-(void) setName:(NSString*) n {
    name = n;
}


@end

Teacher

//
//  Teacher.h
//  DynamicType
//
//  Created by Michael on 2016/9/27.
//  Copyright © 2016年 Michael. All rights reserved.
//

#import "Person.h"

//继承Person
@interface Teacher : Person

-(void) teach;

@end

//
//  Teacher.m
//  DynamicType
//
//  Created by Michael on 2016/9/27.
//  Copyright © 2016年 Michael. All rights reserved.
//

#import "Teacher.h"

@implementation Teacher

-(void) teach {
    NSLog(@"%@教数学",name);
}
@end

isMemberOfClass

Person *person = [[Person alloc] init];
Teacher *teaher = [[Teacher alloc] init];
      
//1.isMemberOfClass判断是否是属于这类的实例,是否跟父类有关系他不管
//yes
if ([teaher isMemberOfClass:[Teacher class]]) {
  NSLog(@"teacher Teacher类的成员");
}
   
//no
if ([teaher isMemberOfClass:[Person class]]) {
  NSLog(@"teacher Person类的成员");
}
   
//no
if ([teaher isMemberOfClass:[NSObject class]]) {
  NSLog(@"teacher NSObject类的成员");
}

isKindOfClass

//2.isKindOfClass判断是否是其子类
//yes
if ([teaher isKindOfClass:[Teacher class]]) {
  NSLog(@"teacher 是Teacher类或子类");
}
   
//yes
if ([teaher isKindOfClass:[Person class]]) {
  NSLog(@"teacher 是Person类或子类");
}
   
//yes
if ([teaher isKindOfClass:[NSObject class]]) {
  NSLog(@"teacher 是NSObject类或子类");
}

判断对象方法

-(BOOL) respondsToSelector: selector 判读实例是否有这样方法
+(BOOL) instancesRespondToSelector: 判断类是否有这个方法。此方法是类方法,不能用在类的对象

respondsToSelector

//3.respondsToSelector判断示例是否有这个方法
   
if ([teaher respondsToSelector:@selector(setName:)]) {
  NSLog(@"有此方法");
}
   
if ([teaher respondsToSelector:@selector(setAge)] == NO) {
  NSLog(@"无此方法");
}

instancesRespondToSelector

//4.instancesRespondToSelector判断类中是否有该方法,不能用在类的对象
   
if ([Person instancesRespondToSelector:@selector(setName:)]) {
  NSLog(@"Person 有此方法");
}
   
if ([Teacher instancesRespondToSelector:@selector(teach)]) {
  NSLog(@"Teacher 有此方法");

}
   
if ([Teacher instancesRespondToSelector:@selector(setName:)]) {
  NSLog(@"Teacher 有此方法");
  
}

Objective-C的id类型

在 Objective-C 中,id类型类似于(void*) ,可以指向任何类的实例。而不需要强制转换。

Teacher *teaher = [[Teacher alloc] init];
id t = teaher;  //id指向Teacher类
[t setName:@"liuguoquan"];
[t teach];
返回顶部