[iOS]多参数方法调用封装

NSObject的performSelector: withObject: withObject:方法顶多支持传2个参数,局限性比较大。

NSInvocation类可以用来执行多个参数的方法。

具体用法,我封装了一个工具类如下:

#import 

NS_ASSUME_NONNULL_BEGIN

@interface NSObject (POInvocation)

- (void)po_performSelector:(SEL)selector target:(id)target withObjects:(NSArray *)objects;

@end

NS_ASSUME_NONNULL_END
#import "NSObject+POInvocation.h"


@implementation NSObject (POInvocation)

- (void)po_performSelector:(SEL)selector target:(id)target withObjects:(NSArray *)objects
{
    NSMethodSignature *signature = [target methodSignatureForSelector:selector];
    
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    invocation.selector = selector;
    invocation.target = self;
    
    if (objects.count>0) {
        [objects enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [invocation setArgument:&obj atIndex:2+idx];
        }];
    }
    
    [invocation invoke];
}

@end

思路:接收一个数组参数,用户在里面定义要传入的参数即可。

调用例子:

[self po_performSelector:@selector(callWithNumber:work:workDic:) target:self withObjects:@[@"188",@"我汽车了",@{@"name":@"hyl"}]];

 

你可能感兴趣的:(iOS)