开发者

@selector with multiple arguments

How does one call an @selector method with multiple arguments?

I have the following

[self performSelector:@selector(changeImage:withString:) withObject:开发者_Python百科A1 withObject:fileString2 afterDelay:0.1];

but get an

unrecognized selector sent to instance

error

My method I am calling is as follows

-(void) changeImage: (UIButton *) button withString: (NSString *) string
{
[button setImage:[UIImage imageNamed:string] forState:UIControlStateNormal];
}


You should use NSInvocation

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
                             [self methodSignatureForSelector:@selector(changeImage:withString:)]];
[invocation setTarget:self];
[invocation setSelector:@selector(changeImage:withString:)];
[invocation setArgument:A1 atIndex:2];
[invocation setArgument:fileString2 atIndex:3];
[NSTimer scheduledTimerWithTimeInterval:0.1f invocation:invocation repeats:NO];


The NSObject class has a performSelector:withObject:afterDelay: method, and the NSObject protocol specifies a performSelector:withObject:withObject: method, but nowhere is there specified a performSelector:withObject:withObject:afterDelay:.

In this case, you'll have to use an NSInvocation to get the functionality you desire. Set up the invocation, and then you can call performSelector:withObject:afterDelay on the invocation itself, using the selector invoke and a nil object.


There is no method for performing a selector with multiple arguments and a delay. You could wrap the button and the string object in a NSDictionary to work around this like this:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:A1,@"button",fileString2,@"string",nil];
[self performSelector:@selector(changeWithDict:) withObject:dict afterDelay:0.1];
//...

-(void)changeWithDict:(NSDictionary *)dict {
    [[dict objectForKey:@"button"] setImage:[UIImage imageNamed:[dict objectForKey:@"string"]] forState:UIControlStateNormal];
}


If you're targeting iOS 4.0+ you could use blocks. Something along the lines of this should do the trick.

// Delay execution of my block for 0.1 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC / 10ull), dispatch_get_current_queue(), ^{
    [self changeImage:A1 withString:fileString2];
});


It's not a good way to get round it, but if you wanted you could modify the method to accept an NSArray, when the object at index 0 is the button and at index 1 is the string.


You are calling performSelector:withObject:withObject:afterDelay:, but that method doesn't exist.

Your only option is performSelector:withObject:withObject:, but you can't specify a delay with that method. If you need a delay, you'd probably have to create a category for NSObject and create a new method yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜