IOS系统反射

反射机制主要是通过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;
@end

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








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值