通过 performSelector ios 调用具有多个参数的方法

Call method with multiple parameter by performSelector ios

这是我的方法,有两个参数:imgArrayandDurationArray。 我想在我的 else 部分中通过 performSelector 使用相同的两个参数调用相同的方法。我怎么称呼它?提前致谢。

-(void) imageAnimationWithImage:(NSArray *) imgArray andDurationArray:(NSArray *) durationArr
{
    if (count == imgarray.count)
    {
        count = 0;
        [self imageAnimationWithImage:imgarray andDurationArray:durationArr];
    }
    else
    {
        emoImageView.image = [UIImage imageNamed:[imgarray objectAtIndex:count]];
        [self performSelector:@selector(imageAnimationWithImage:andDurationArray:) withObject:imgarray withObject:durationArr afterDelay:[[durationArr objectAtIndex:count] doubleValue]];
        count++;
    }
}

你为什么不使用NSInvocation它更适合多个参数,其次注意你正在创建一个具有高递归风险的方法

  NSInteger delay = [[durationArr objectAtIndex:count] doubleValue];
  SEL aSelector = @selector(imageAnimationWithImage:andDurationArray:);
  NSMethodSignature *signature = [self methodSignatureForSelector:aSelector];
  NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
  [invocation setTarget:self];
  [invocation setSelector:aSelector];
  [invocation setArgument:&imgarray atIndex:2];
  [invocation setArgument:&durationArr atIndex:3];

  [invocation performSelector:@selector(invoke) withObject:nil afterDelay:delay];

方法 performSelector:withObject:afterDelay 仅适用于 0 或 1 个参数。您可以将参数打包到字典中并传递它,或者使用 dispatch_after,它继承了封闭范围,因此不需要参数。

使用dispatch_after。更容易:

double delay = [[durationArr objectAtIndex:count] doubleValue];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [self imageAnimationWithImage:imgarray andDurationArray:durationArr];
});