How do I pass more than one parameter to the selector in 'scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:'

StackOverflow https://stackoverflow.com/questions/9515591

Question

I know user info is used to pass a parameter, but how do I pass more than one of these?

I'm guessing I have to use an object, but as I am fairly new to objective-c I don't really know if this is right and how to go about it?

Thanks!

Was it helpful?

Solution

Create a wrapper object, an NSArray or NSDictionary with the multiple objects you need to pass and pass that wrapper object in userInfo. On the receiver retrieve the objects from the wrapper object.

Example code using a NSDictionary for the wrapper:

Calling code:

NSString *obj1 = @"string1"; 
NSString *obj2 = @"string2"; 
NSDictionary *wrapper = [NSDictionary dictionaryWithObjectsAndKeys:obj1, @"Object1", obj2, @"Object2", nil];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:wrapper repeats:NO];

Receiving timer code:

- (void)timerFireMethod:(NSTimer*)theTimer {
    NSDictionary *wrapper = (NSDictionary *)[theTimer userInfo];
    NSString * obj1 = [wrapper objectForKey:@"Object1"];
    NSString * obj2 = [wrapper objectForKey:@"Object2"];
    // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top