050.performSelector 动态调用方法

本文介绍 Objective-C 中如何使用 performSelector 进行动态方法调用,并演示了不同参数数量的方法调用实例。
---------------  FKCar.h  ---------------
#import <Foundation/Foundation.h>
@interface FKCar : NSObject
@end
---------------  FKCar.m  ---------------
#import "FKCar.h"
@implementation FKCar
- (
void) move
{
    
NSLog(@"汽车在路上行驶");
}
@end
---------------  main.m  ---------------
#import <Foundation/Foundation.h>
#import 
"FKCar.h"
int main()
{
    
FKCar* car = [[FKCar allocinit];
    [car 
performSelector:@selector(move)];
}

、本节代码涉及到的知识点:
1.move方法虽然没有在@interface部分声明,但我们依然可以通过动态机制调用。
2.performSelector是运行时系统负责去找方法的,在编译时候不做任何校验。
3.以下代码分别示范了没有参数、一个参数、两个参数情况下的写法:
- (id)performSelector:(SEL)aSelector;
- (
id)performSelector:(SEL)aSelector withObject:(id)object;
- (
id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;


- (
void)methodNoParam
{
    NSLog(
@"methodNoParam");
}

- (
void)methodWithOneParam:(id)paramFirst
{
    NSLog(@"methodWithOneParam: %@", paramFirst);
}

- (
void)methodWithParams:(id)paramFirst andParamSecond:(id) paramSecond
{
    NSLog(
@"methodWithOneParam: %@,%@", paramFirst,paramSecond);
}


BOOL isNoParam= [self.selfViewControllerDelegate respondsToSelector:@selector(methodNoParam)];
if (isNoParam)
{
    [self.selfViewControllerDelegate performSelector:@selector(methodNoParam)];
}


BOOL isOneParam= [self.selfViewControllerDelegate respondsToSelector:@selector(methodWithOneParam:)];
if (isOneParam)
{
    [self.selfViewControllerDelegate performSelector:@selector(methodWithOneParam:) withObject:@"firsht"];
}


BOOL isParams= [self.selfViewControllerDelegate respondsToSelector:@selector(methodWithParams: andParamSecond:)];
if (isParams)
{
    [self.selfViewControllerDelegate performSelector:@selector(methodWithParams: andParamSecond:) withObject:@"first" withObject:@"second"];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值