Multithreaded programming is the best way to prevent the main thread from clogging, increasing the efficiency of running, and so on. But the original multithreading method has many problems, including the thread lock Deng. In cocoa, Apple provides a nsoperation class that provides an excellent multithreaded programming approach.
This article introduces the subset of Nsoperation, the simple method of nsinvocationoperation:
@implementation MyCustomClass
-(void) Launchtaskwithdata: (ID) data
{
Creates a Nsinvocationoperation object and initializes it to the method
Here, the value after the selector parameter is the method you want to run in another thread (function, methods)
Here, the value after object is the data that you want to pass to the previous method
nsinvocationoperation* Theop = [[Nsinvocationoperation alloc] Initwithtarget:self
Selector: @selector (mytaskmethod:) object:data];
The operation "Operation" We have established is added to the local program's Shared Queue (the method will be executed immediately upon accession)
More often, we build our own "operations" queues.
[[Myappdelegate Sharedoperationqueue] addoperation:theop];
}
This is the "method" that really runs on another thread
-(void) Mytaskmethod: (ID) data
{
Perform the task.
}
@end a Nsoperationqueue action queue, which is equivalent to a thread manager, not a thread. Because you can set the number of threads in this thread manager that can run in parallel, and so on. The following is the establishment and initialization of an action queue:
@interface Myviewcontroller:uiviewcontroller {
Nsoperationqueue *operationqueue;
Declaring the queue in a header file
}
@end
@implementation Myviewcontroller
-(ID) init
{
self = [super init];
if (self) {
Operationqueue = [[Nsoperationqueue alloc] init]; Initializing an action queue
[Operationqueue setmaxconcurrentoperationcount:1];
The queue is limited here to run only one thread at a time
This queue is ready to use.
}
return self;
}
-(void) dealloc
{
[Operationqueue release];
As Alan often says, we are good citizens of the program and need to free up memory.
[Super Dealloc];
}
@end A brief introduction, you can actually find this method is very simple. Many times we use multithreading just to prevent the main thread from clogging, and nsinvocationoperation is the simplest multithreaded programming that is often used in iphone programming.
///////////////////////////////////////////////////////////////////////////////////////////////////
1 in the main line Chengri add a loading screen ...
2 {
3 [window addsubview:view_loading];
4 [Nsthread detachnewthreadselector: @selector (init_backup:) totarget:self Withobject:nil];
5}
You can update UI elements by Performselectoronmainthread, such as setting progress bars, and so on. Finally eliminate the loading screen, load into the main view.
7-(void) Init_backup: (ID) sender
8 {
9 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
10
11//...
int i = status;
[Self Performselectoronmainthread: @selector (show_loading:) withobject:[nsnumber numberwithint:i] Waituntil done: NO];
14
[View_loading Removefromsuperview];
[Window AddSubview:tabcontroller_main.view];
[Pool release];
18}
Using the iphone's multi-threaded implementation and thread synchronization
As you can see from the definition of interfaces, Nsthread, like most iphone interface objects, can be initialized in two ways:
One uses the Initwithtarget: (ID) Target selector: (SEL) Selector object: (ID) argument, but takes responsibility for the retain Count is 0 o'clock to call the object's release method to clean the object.
The other uses the so-called convenient method, which is detachnewthreadselector, which generates a thread directly and starts it without being responsible for thread cleanup.
#import <UIKit/UIKit.h>
@interface Sellticketsappdelegate:nsobject <UIApplicationDelegate> {
int tickets;
int count;
nsthread* Ticketsthreadone;
nsthread* Ticketsthreadtwo;
nscondition* ticketscondition;
UIWindow *window;
}
Then add the following code in the implementation:
Sellticketsappdelegate.m
Selltickets
//
//
#import "SellTicketsAppDelegate.h"
@implementation Sellticketsappdelegate
@synthesize window;
-(void) applicationdidfinishlaunching: (uiapplication *) Application {
Tickets = 100;
Count = 0;
Lock Object
Ticketcondition = [[Nscondition alloc] init];
Ticketsthreadone = [[Nsthread alloc] initwithtarget:self selector: @selector (run) Object:nil];
[Ticketsthreadone setname:@ "Thread-1"];
[Ticketsthreadone start];
Ticketsthreadtwo = [[Nsthread alloc] initwithtarget:self selector: @selector (run) Object:nil];
[Ticketsthreadtwo setname:@ "Thread-2"];
[Ticketsthreadtwo start];
[Nsthread detachnewthreadselector: @selector (Run) totarget:self Withobject:nil];
Override point for customization after application launch
[Window makekeyandvisible];
}
-(void) run{
while (TRUE) {
Locked
[Ticketscondition Lock];
if (Tickets > 0)
{
[Nsthread sleepfortimeinterval:0.5];
Count = 100-tickets;
NSLog (@ "The current number of votes is:%d, sold:%d, thread name:%@", Tickets,count,[[nsthread CurrentThread] name));
tickets--;
}else
{
Break
}
[Ticketscondition unlock];
}
}
-(void) Dealloc {
[Ticketsthreadone release];
[Ticketsthreadtwo release];
[Ticketscondition release];
[Window release];
[Super Dealloc];
}
@end
-------------------------------------------------------------------------------------
Defined
#import <UIKit/UIKit.h>
@interface Threadsyncsampleviewcontroller:uiviewcontroller {
int _threadcount;
Nscondition *_mycondition;
}
@end
The implementation file is as follows:
#import "ThreadSyncSampleViewController.h"
@implementation Threadsyncsampleviewcontroller
/*
The designated initializer. Override to perform setup this is required before the view is loaded.
-(ID) Initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *) Nibbundleornil {
if (self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil]) {
Custom initialization
}
return self;
}
*/
/*
Implement Loadview to create a view hierarchy programmatically, without using a nib.
-(void) Loadview {
}
*/
Implement Viewdidload to did additional setup after loading the view, typically from a nib.
-(void) Viewdidload {
[Super Viewdidload];
//
_mycondition = nil;
//
_mycondition = [[Nscondition alloc] init];
//
Nstimer *timer = [Nstimer scheduledtimerwithtimeinterval:30
Target:self
Selector: @selector (Threadtester)
Userinfo:nil
Repeats:yes];
[Timer fire];
}
-(void) threadtester{
[_mycondition Lock];
_threadcount =-2;
If you have n a thread to wait on, place it as-n
[_mycondition unlock];
//
NSLog (@ "");
NSLog (@ "------------------------------------------------------------------------------");
[Nsthread detachnewthreadselector: @selector (Threadone) totarget:self Withobject:nil];
[Nsthread detachnewthreadselector: @selector (threadtwo) totarget:self Withobject:nil];
[Nsthread detachnewthreadselector: @selector (threadthree) totarget:self Withobject:nil];
Return
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service