how can i pass an int value through a selector method?

人走茶凉 提交于 2019-12-29 04:45:10

问题


I want to pass an int value from my selector method, but the selector method takes only an object type parameter.

int y =0;
[self performselector:@selector(tabledata:) withObject:y afterDelay:0.1];

Method execution is here

-(int)tabledata:(int)cellnumber {
   NSLog(@"cellnumber: %@",cellnumber);
   idLabel.text = [NSString stringWithFormat:@"Order Id: %@",[[records objectAtIndex:cellnumber] objectAtIndex:0]];
}

but I am not getting exact integer value in my method, I am only getting the id value.


回答1:


The easiest solution, if you 'own' the target selector, is to wrap the int argument in an NSNumber:

-(int)tabledata:(NSNumber *)_cellnumber {
    int cellnumber = [_cellnumber intValue];
    ....
}

To call this method you would use:

[self performselector:@selector(tabledata:) withObject:[NSNumber numberWithInt:y] afterDelay:0.1];



回答2:


This works also for an int parameter, which is especially useful, if you are unable to change the signature of the selector you want to perform.

SEL sel = @selector(tabledata:);

NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:sel];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.selector = sel;
// note that the first argument has index 2!
[invocation setArgument:&y atIndex:2];

// with delay
[invocation performSelector:@selector(invokeWithTarget:) withObject:self afterDelay:0.1];



回答3:


Instead of your performSelector:withObject:afterDelay:, use an NSTimer, thusly:

int y = 0;
[NSTimer scheduledTimerWithTimeInterval:0.1 repeats:NO block:^(NSTimer *timer) {
    [self tabledata:y];
}];

You can pass whatever you want in the timer block.



来源:https://stackoverflow.com/questions/7899223/how-can-i-pass-an-int-value-through-a-selector-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!