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;}








0 0
原创粉丝点击