Here I am explain you how to create threading in iphone. Here we will create two separate threads where one will increase counter and another will decrease counter. I am giving you complete code snippets as well as source code also.
devangViewController .h
#import <UIKit/UIKit.h>devangViewController .m implementation file
@interface devangViewController : UIViewController
{ NSOperationQueue *operationQueue;
}
@property (weak, nonatomic) IBOutlet UILabel *counter1_lbl;
@property (weak, nonatomic) IBOutlet UILabel *counter2_lbl;
-(void)counter1;
-(void)counter2;
@end
#import "devangViewController.h"
@interface devangViewController ()
@end
@implementation devangViewController
@synthesize counter1_lbl,counter2_lbl;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
operationQueue = [NSOperationQueue new];
// Create a new NSOperation object using the NSInvocationOperation subclass.
// Tell it to run the counterTask method.
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(counter1)
object:nil];
// Add the operation to the queue and let it to be executed.
[operationQueue addOperation:operation];
operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(counter2)
object:nil];
[operationQueue addOperation:operation];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)counter1{
// Make a BIG loop and every 100 repeats let it update the label1 UILabel with the counter's value.
for (int i=0; i<100000; i++) {
// Notice that we use the performSelectorOnMainThread method here instead of setting the label's value directly.
// We do that to let the main thread to take care of showing the text on the label
// and to avoid display problems due to the loop speed.
[counter1_lbl performSelectorOnMainThread:@selector(setText:)
withObject:[NSString stringWithFormat:@"%d", i]
waitUntilDone:YES];
}
// When the loop gets finished then just display a message.
[counter1_lbl performSelectorOnMainThread:@selector(setText:) withObject:@"Thread #1 Complete " waitUntilDone:NO];
}
-(void)counter2{
// We need a custom color to work with.
for (int i=100000; i>0; i--) {
// Notice that we use the performSelectorOnMainThread method here instead of setting the label's value directly.
// We do that to let the main thread to take care of showing the text on the label
// and to avoid display problems due to the loop speed.
[counter2_lbl performSelectorOnMainThread:@selector(setText:)
withObject:[NSString stringWithFormat:@"%d", i]
waitUntilDone:YES];
}
// When the loop gets finished then just display a message.
[counter2_lbl performSelectorOnMainThread:@selector(setText:) withObject:@"Thread #2 Complete " waitUntilDone:NO];
}
@end
0 comments:
Post a Comment