objective-c 反射

使用很简单,直接上代码


#import <Foundation/Foundation.h>
#import <objc/message.h>
@interface Car : NSObject

@end

@implementation  Car

-(void)move:(NSNumber*)count{
 
    for (int i=0; i<[count intValue]; i++) {
        NSLog(@"car  move...%d ",i);
    }
    
    NSLog(@"\n\n");
}


-(double)addSpeed:(double)factor{
    
    [self performSelector:@selector(move:) withObject:[NSNumber  numberWithInt:2] ];
    
    [self performSelector:NSSelectorFromString(@"move:") withObject:[NSNumber numberWithInt:2] ];
    
    objc_msgSend(self , @selector(move:) , [NSNumber numberWithInt:3] );
    
    objc_msgSend(self , NSSelectorFromString(@"move:") , [NSNumber numberWithInt:2] );
    
    return 100*factor;
}

@end



int main(int argc, const char * argv[]) {
    @autoreleasepool {
       
//        [[[Car alloc]init] addSpeed:1.0];
        
       Class clz= NSClassFromString(@"Car");//反射得到类
        
        id car=[[clz alloc]init];//得到Car对象
        
        [car addSpeed:5.2];
    }
    return 0;
}

打印如下

2015-09-20 16:51:49.030 testt[880:139167] car  move...0 
2015-09-20 16:51:49.032 testt[880:139167] car  move...1 
2015-09-20 16:51:49.032 testt[880:139167] 

2015-09-20 16:51:49.032 testt[880:139167] car  move...0 
2015-09-20 16:51:49.033 testt[880:139167] car  move...1 
2015-09-20 16:51:49.033 testt[880:139167] 

2015-09-20 16:51:49.033 testt[880:139167] car  move...0 
2015-09-20 16:51:49.033 testt[880:139167] car  move...1 
2015-09-20 16:51:49.033 testt[880:139167] car  move...2 
2015-09-20 16:51:49.033 testt[880:139167] 

2015-09-20 16:51:49.034 testt[880:139167] car  move...0 
2015-09-20 16:51:49.034 testt[880:139167] car  move...1 
2015-09-20 16:51:49.034 testt[880:139167] 


注意导包   #import <objc/message.h>

objc_msgSend可能会提示参数太多,按下图操作就可以了objective-c 反射_第1张图片


你可能感兴趣的:(Objective-C)