1. IOS has three kinds of multithreaded programming technologies, which are: 1. NSThread

Cocoa NSOperation (Use of NSOperation and NSOperationQueue for iOS Multithreaded Programming)

Grand Central Dispatch(iOS Multithreaded programming Grand Central Dispatch(GCD) introduction and use)

These three programming methods are from top to bottom, and the level of abstraction is from low to high. The higher the abstraction is, the easier it is to use, which is also the most recommended by Apple.

In this article, we mainly introduce and use NSThread. We will continue to explain and use NSThread in chapter 2 and chapter 3.

1.2 Disadvantages of the three methods: NSThread:

Advantages: NSThread is lighter than the other two

Disadvantages: need to manage their own thread life cycle, thread synchronization. Locking data for thread synchronization has some system overhead

NSThread implements the following three technologies:

Technology

Description

Cocoa threads

Cocoa implements threads using the NSThread class. Cocoa also provides methods on NSObject for spawning new threads and executing code on already-running threads. For more information, See “Using NSThread” and “Using NSObject to Spawn a Thread.”

POSIX threads

POSIX threads provide a C-based interface for creating threads. If you are not writing a Cocoa application, this is the best choice for creating threads. The POSIX interface is relatively simple to use and offers ample Flexibility for configuring your Threads. For more information, see “Using POSIX Threads”

Multiprocessing Services

Multiprocessing Services is a legacy C-based interface used by applications transitioning from older versions of Mac OS. This technology is available in OS X only and should be avoided for any new development. Instead, you should use the NSThread class or POSIX threads. If you need more information on this technology, see Multiprocessing Services Programming Guide.

Cocoa Thread technology is generally used.

Cocoa operation

Advantages: You don’t need to worry about thread management, data synchronization, and can focus on what you need to do.

The relevant classes for Cocoa Operation are NSOperation, NSOperationQueue. NSOperation is an abstract class. To use it, you must use its subclasses. You can implement it or use the two subclasses it defines: NSInvocationOperation and NSBlockOperation. Create an NSOperation subclass and add the object to the NSOperationQueue for execution.

GCD

Grand Central Dispatch (GCD) is a multi-core programming solution developed by Apple. It won’t be available until iOS4.0 starts. GCD is an efficient and powerful alternative to technologies such as NSThread, NSOperationQueue, and NSInvocationOperation. Now that iOS has been upgraded to 6, there is no need to worry that this technology will not work.

After the introduction of these three multithreaded programming methods, we will first introduce the use of NSThreads.

2.1 NsThreads can be directly created in two ways:

  • (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
  • (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument

The first is an instance method and the second is a class method

[cpp] view plain copy

1 [NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil]; 2 NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:nil]; 3 [myThread start]; 2.2 Significance of Arguments: Selector: a method executed by a thread that takes only one argument and does not return a value.

Target: Selector object to which the message is sent

Argument: The unique argument passed to target. It can also be nil

The first way is to directly create a thread and start running the thread. The second way is to create a thread object first and then run the thread operation. Before running the thread operation, you can set the thread information such as the priority of the thread

PS: 2.3 don’t explicitly create a thread method: use NSObject class methods performSelectorInBackground: withObject: Create a thread: [Obj performSelectorInBackground: @ the selector (doSomething) withObject: nil];

Create a new project and place an imageView control on the XIB file. Hold down the Control key and drag to the viewControll

Create an imageView IBOutlet in the er.h file

ViewController.m

[cpp] view plain copy

//

// ViewController.m

// NSThreadDemo

//

// Created by rongfzh on 12-9-23.

// Copyright (c) 2012年 rongfzh. All rights reserved.

//

#import “ViewController.h”

#define kURL @”http://avatar.csdn.net/2/C/D/1_totogo2010.jpg”

@interface ViewController ()

@end

@implementation ViewController

-(void)downloadImage:(NSString *) url{

NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];  

UIImage *image = [[UIImage alloc]initWithData:data];  

if(image == nil){  

      

}else{  

    [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];  

}  
Copy the code

}

-(void)updateUI:(UIImage*) image{

self.imageView.image = image;  
Copy the code

}

  • (void)viewDidLoad

{

[super viewDidLoad];  
Copy the code

// [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:kURL];

NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(downloadImage:) object:kURL];  

[thread start];  
Copy the code

}

  • (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];  

// Dispose of any resources that can be recreated.  
Copy the code

}

@end

2.4.2 Communication between Threads How to notify the main thread to update the interface after downloading the picture?

[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];

PerformSelectorOnMainThread is NSObject method, in addition to update data on the main thread, can also update other threads, such as:

Use: performSelector: onThread: withObject: waitUntilDone:

Run download picture:

The image is downloaded.

Let’s show a classic example of how to synchronize nsthreads:

.h

[cpp] view plain copy

#import <UIKit/UIKit.h>

@class ViewController;

@interface AppDelegate : UIResponder

{

int tickets;  

int count;  

NSThread* ticketsThreadone;  

NSThread* ticketsThreadtwo;  

NSCondition* ticketsCondition;  

NSLock *theLock;  
Copy the code

}

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@end

[cpp] view plain copy

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

tickets = 100; count = 0; theLock = [[NSLock alloc] init]; TicketsCondition = [[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]; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES;Copy the code

}

  • (void)run{

    while (TRUE) {

    / / lockCopy the code

// [ticketsCondition lock];

[theLock lock]; If (tickets > = 0) {[NSThread sleepForTimeInterval: 0.09]; count = 100 - tickets; NSLog(@" current ticket :%d, sold :%d, thread name :%@",tickets,count,[[NSThread currentThread] name]); tickets--; }else{ break; } [theLock unlock];Copy the code

// [ticketsCondition unlock];

}  
Copy the code

}

If there is no thread synchronization lock, the sell vote might be -1. Thread synchronization with lock guarantees data correctness. In the example above, I used two types of locks: NSCondition and NSLock. I’ve commented out ns conditions.

Threads execute in order they can all pass

[ticketsCondition signal]; Means of sending signals in one thread to wake up another thread to wait.Copy the code

Such as:

[cpp] view plain copy

#import “AppDelegate.h”

#import “ViewController.h”

@implementation AppDelegate

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

tickets = 100; count = 0; theLock = [[NSLock alloc] init]; TicketsCondition = [[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 *ticketsThreadthree = [[NSThread alloc] initWithTarget:self selector:@selector(run3) object:nil]; [ticketsThreadthree setName:@"Thread-3"]; [ticketsThreadthree start]; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES;Copy the code

}

-(void)run3{

while (YES) {  

    [ticketsCondition lock];  

    [NSThread sleepForTimeInterval:3];  

    [ticketsCondition signal];  

    [ticketsCondition unlock];  

}  
Copy the code

}

  • (void)run{

    while (TRUE) {

    [ticketsCondition lock]; [ticketsCondition wait]; [theLock lock]; If (tickets > = 0) {[NSThread sleepForTimeInterval: 0.09]; count = 100 - tickets; NSLog(@" current ticket :%d, sold :%d, thread name :%@",tickets,count,[[NSThread currentThread] name]); tickets--; }else{ break; } [theLock unlock]; [ticketsCondition unlock];Copy the code

    }

}

We can simplify the use of NSLocks by using @synchronized, so that we don’t have to explicitly write code to create an NSLock, lock, and unlock the lock.

  • (void)doSomeThing:(id)anObj { @synchronized(anObj) { // Everything between the braces is protected by the @synchronized directive. } }

For ios knowledge or comprehensive interview tips add QQ: 2645837520