首页 > 代码库 > 【Object C】 反射机制

【Object C】 反射机制

Object-C 也提供了类似Java的反射机制。通过以下三种方式与运行环境交互:
1、直接通过Object-C源代码
2、通过NSObject中定义的方法:
isKindOfClass
isMemberOfClass
responseToSelector:判断该实例是否调用指定方法
3、直接调用运行时函数进行动态编程

#import<Foundation/Foundation.h>
#import
"DCApple.h"
intmain(intargc, const char * argv[]) {
   
@autoreleasepool {
       
// insert code here...
       
NSLog(@"Hello, World!");
       
// 通过字符串来获取Class
        Class clazz =
NSClassFromString(@"NSDate");
       
NSLog(@"%@", clazz);
       
// 直接使用Class来创建对象
       
id date = [[clazz alloc] init];
       
NSLog(@"%@", date);
       
// 通过对象来获取Class
       
NSLog(@"%@", [date class]);
       
// 通过类来获取class
       
NSLog(@"%d", clazz == NSDate.class);
    }
   
return 0;
}

===>>
2014-12-01 09:06:25.916 reflection[1179:303] Hello, World!
2014-12-01 09:06:25.917 reflection[1179:303] NSDate
2014-12-01 09:06:25.924 reflection[1179:303] 2014-12-01 01:06:25 +0000
2014-12-01 09:06:25.925 reflection[1179:303] __NSDate
2014-12-01 09:06:25.925 reflection[1179:303] 1
Program ended with exit code: 0

检查继承关系
conformsToProtocol:传入一个Protocol 参数,用于判断该类及其子类的实例。
//
//  main.m
//  reflection
//
//  Created by mac on 14-12-1.
//  Copyright (c) 2014mac. All rights reserved.
//

#import<Foundation/Foundation.h>
#import
"DCApple.h"
intmain(intargc, const char * argv[]) {
    @autoreleasepool {
       // 判断对象是否为某个类及其子类的实例
       
NSLog(@"app是否为DCApple及其子类的实例:%d",
              [app
isKindOfClass: DCApple.class]);
       
NSLog(@"app是否为NSObject及其子类的实例:%d",
              [app
isKindOfClass: NSObject.class]);
       
NSLog(@"app2是否为DCApple及其子类的实例:%d",
              [app2
isKindOfClass: DCApple.class]);
       
NSLog(@"app2是否为NSObject及其子类的实例:%d",
              [app2
isKindOfClass: NSObject.class]);
       
// 判断对象是否实现了指定协议
       
NSLog(@"app是否实现DCEatable协议:%d",
              [app
conformsToProtocol:@protocol(DCEatable)]);
       
NSLog(@"app2是否实现了DCEatable协议:%d",[app2conformsToProtocol:@protocol(DCEatable)]);
       
    }
   
return 0;
}
=====>>
2014-12-01 14:07:26.220 reflection[2195:303] DCApple
2014-12-01 14:07:26.220 reflection[2195:303] DCApple1
2014-12-01 14:07:26.221 reflection[2195:303] app
是否为DCApple的实例:1
2014-12-01 14:07:26.221 reflection[2195:303] app
是否为NSObject的实例:0
2014-12-01 14:07:26.222 reflection[2195:303] app2
是否为NSObject的实例:0
2014-12-01 14:07:26.222 reflection[2195:303] app2
是否为DCApple的实例:0
2014-12-01 14:07:26.223 reflection[2195:303] app2
是否为DCApple的实例:1
2014-12-01 14:07:26.223 reflection[2195:303] app
是否为DCApple及其子类的实例:1
2014-12-01 14:07:26.224 reflection[2195:303] app
是否为NSObject及其子类的实例:1
2014-12-01 14:07:26.224 reflection[2195:303] app2
是否为DCApple及其子类的实例:1
2014-12-01 14:07:26.225 reflection[2195:303] app2
是否为NSObject及其子类的实例:1
2014-12-01 14:07:26.225 reflection[2195:303] app
是否实现DCEatable协议:1
2014-12-01 14:07:26.225 reflection[2195:303] app2
是否实现了DCEatable协议:1
Program ended with exit code: 0

【Object C】 反射机制