IOS系统反射
来源:互联网 发布:g20对杭州的影响 知乎 编辑:程序博客网 时间:2024/06/14 03:18
反射机制主要是通过NSClassFromString,通过字符串获取类返回Class对象
NSSelectorFromString,通过字符串来获取函数选择器SEL。可以携带两个参数,参见头文件定义。
NSObject.h
/**
* Performs the specified selector. The selector must correspond to a method
* that takes no arguments.
*/
- (id) performSelector: (SEL)aSelector;
/**
* Performs the specified selector, with the object as the argument. This
* method does not perform any automatic unboxing, so the selector must
* correspond to a method that takes one object argument.
*/
- (id) performSelector: (SEL)aSelector
withObject: (id)anObject;
/**
* Performs the specified selector, with the objects as the arguments. This
* method does not perform any automatic unboxing, so the selector must
* correspond to a method that takes two object arguments.
*/
- (id) performSelector: (SEL)aSelector
withObject: (id)object1
withObject: (id)object2;
对某个类对象执行选择操作(也就是执行类实例的成员函数),该函数也就是SEL(选择器)
获取选择器也可以通过反射功能得到NSSelectorFromString。返回一个SEL对象。
查看演示代码:
#include <Foundation/Foundation.h>#include <objc/runtime.h>@interface Member : NSObject{ NSString* _name; int _age;}@property(copy, nonatomic)NSString* _name;@property(readwrite,nonatomic)int _age;- (id) init;- (void) show;- (void) setName: (NSString*) name;@end@implementation Member- (id) init{ if(self = [super init]) { NSLog(@"Member initialized"); _name = nil; _age = 0; }}- (void) show{ NSLog(@"name=%@", _name);}- (void) setName:(NSString*) name{ _name = name;}@synthesize _name,_age;@endint main(){ id mp = [[NSAutoreleasePool alloc] init]; NSLog(@"Hello world!\n"); NSString *className = @"Member";
//setName:如果选择器带有参数必须携带“:”
NSString *methodName = @"setName:"; id obj = [[NSClassFromString(className) alloc] init]; //[obj setName: @"onetest"]; //[obj show]; [obj performSelector: NSSelectorFromString(methodName) withObject: @"test"]; [obj show]; getchar(); [mp drain]; return 0;}
- IOS系统反射
- ios反射
- ios-反射
- IOS提供的反射
- iOS反射机制
- iOS实现反射机制
- IOS反射 class_copyPropertyList
- iOS实现反射机制
- ios中的反射
- iOS反射机制
- IOS 反射机制
- iOS反射机制
- iOS反射机制
- [IOS 开发] 反射
- iOS之反射
- iOS反射机制
- ios中的反射
- iOS 反射操作
- C++容器/迭代器
- 八叉树
- [华为机试]朋友圈信息转发
- Android 自定义ImageView支持缩放,拖拽,方便复用
- Maurits Cornelis Escher
- IOS系统反射
- 自己创建maven项目工程说明,参考别人的
- WF 系列--WF基础
- 京东2013研发笔试卷
- 黑马程序员——OC热身——NSString、NSMutableString
- 对汇编中寄存器的认识
- Android你好!!
- jquery api的整体解读
- 粗略整理IOS招聘要求