Hi how can I fire functions and methods in a queue in Objective C ? I mean something like this :
method 1 then method 2 then method 3 , Should I use NSThread
?
Hi how can I fire functions and methods in a queue in Objective C ? I mean something like this :
method 1 then method 2 then method 3 , Should I use NSThread
?
One way is to have a Queue
or Stack
of function pointers, then execute and pop the topmost method until no methods are left. Obviously, you can do this with an array and a currentIndex
variable as well (increment currentIndex
from 0
to arraySize - 1
, executing the function pointer at myArray[currentIndex]
each time). See Function Pointers in Objective C for more details on the function pointers themselves.
I have a different solution that involved in using GCD Serial Queues and NSSelectorFromString
method.
1st: Create an array with your methods names
2nd: Create a GCD Serial Queue
3rd: Using NSSelectorFromString to convert method name string to method and insert it into the serial Q using the a for loop, etc.
Here is the complete tested code:
- (IBAction)buttonSerialQPressed:(id)sender
{
dispatch_queue_t serialdQueue;
serialdQueue = dispatch_queue_create("com.mydomain.testbed.serialQ", NULL);
NSArray *arrayMethods = [NSArray arrayWithObjects:@"method1", @"method2", @"method3", nil];
for (NSString *methodName in arrayMethods)
{
dispatch_async(serialdQueue, ^{
SEL myMethod = NSSelectorFromString(methodName);
[self performSelector:myMethod];
});
}
}
-(void)method1
{
for (int i=0; i<1000; i++)
{
NSLog(@"method1 i: %i", i);
}
}
-(void)method2
{
for (int i=0; i<10; i++)
{
NSLog(@"method2 i: %i", i);
}
}
-(void)method3
{
for (int i=0; i<100; i++)
{
NSLog(@"method3 i: %i", i);
}
}
I would use NSOperationQueue. You can set it run one operation at a time, in which case it will proceed step by step through the method calls you want. You can use NSInvocationOperation to create operations out of method calls.