3

我创建了一个动作

-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event

就像这样:

self.moveAction = [CCSequence actions:                          
                   [CCMoveTo actionWithDuration:moveDuration position:touchLocation],
                   [CCCallFunc actionWithTarget:self selector:@selector(guyMoveEnded)],
                   nil
                  ];

但现在,我想通过以下方式自动调用以下方法@selector

-(void)guyMoveEnded:(BOOL)flag AndWhere:(CGPoint)where Andtime:(float)time{
    //do something...
}

我该怎么做?请帮助我,我对选择器感到困惑。

谢谢!

4

4 回答 4

10

您可以将参数添加到 a 中NSArray,然后将其作为参数提供给您的选择器:

NSArray *params = [NSArray arrayWithObjects:@"a str", [NSNumber numberWithInt:42],myObj];
[self performSelector:@selector(myMethod:)withObject:params];

然后解压缩方法中的参数:

-(void)myMethode:(NSArray*)params
{
    NSString *strArg = [params objectAtIndex:0];
    NSNumber * numVal = [params objectAtIndex:1];
    NSObject *objArg = [params objectAtIndex:2];
    int intArg = [numVal intValue];
    .
    .
    .   
}
于 2012-07-27T07:24:33.887 回答
3

当您需要传递超过 2 个参数时,Apple 建议使用NSInvocation 。这是一个很好的例子:NSInvocation for Dummies?

该答案的简短摘要,没有任何解释:

// Prepare the object
NSMethodSignature * mySignature = [NSMutableArray 
    instanceMethodSignatureForSelector:@selector(addObject:)];
NSInvocation * myInvocation = [NSInvocation
    invocationWithMethodSignature:mySignature];

// Set selector and object
[myInvocation setTarget:myArray];
[myInvocation setSelector:@selector(addObject:)];

// Set arguments
[myInvocation setArgument:&myString atIndex:2];

// Invoke it
[myInvocation invoke];

它不仅仅是使用 调用选择器的代码performSelector:,但它允许您使用任意数量的参数调用方法。正如 Cipramill 建议的那样,如果您无法更改签名以减少参数计数,这将特别有用。

于 2012-07-27T07:41:38.467 回答
1

使用您的参数准备一个 NSDictionary 对象并将该字典传递给您的选择器,您可以从字典中获取方法中的值。以下供参考:

 "NSDictionary *dictionary = nil;
  BOOL flag = YES;
  CGFloat time;
  CGPoint pt;
 [dictionary setValue:flag forKey:FIRSTPARAM];
  [dictionary setValue:time forKey:SECONDPARAM];
  [dictionary setObject:point forKey:THIRDPARAM];
[self performSelector:@selector(methodName:) withObject:dictionary];

"

您可以为该类的对象创建自定义类。

于 2012-07-27T07:50:03.303 回答
-1
[favProductCell.btnAddtoCart addTarget:self action:@selector(arrayForAddToCart:) forControlEvents:UIControlEventTouchUpInside];

[favProductCell.btnAddtoCart setTag:indexPath.row];

-(void)arrayForAddToCart:(id)sender
{
    if (![self.addToCartProductIdArray containsObject:self.favoriteProductArray[[sender tag]]])
        [self.addToCartProductIdArray addObject:self.favoriteProductArray[[sender tag]]];
}
于 2014-03-06T06:58:54.770 回答