多線程 異步處理

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    
     //多線程
    // 1
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(mutable1) object:nil];;
    [thread start];
    [thread release];
    // 2
    [NSThread detachNewThreadSelector:@selector(mutable1) toTarget: self withObject:nil];
    
    // 3 NSOBject 線程
    [self performSelectorInBackground:@selector(mutable1) withObject:nil];
    
    // 4 block 線程
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];
    [operationQueue addOperationWithBlock:^{
        NSLog(@"do some ...");
    }];
    
    // 5 添加一個線程 到線程隊列, 可以添加多個,有最大線程數,
    NSOperationQueue *operationQueue2 = [[NSOperationQueue alloc]init];
    //線程併發數
    operationQueue2.maxConcurrentOperationCount = 1;
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(mutable1) object:nil];
    [operationQueue2 addOperation:operation];
    NSInvocationOperation *operation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(mutable1) object:nil];
    [operationQueue2 addOperation:operation2];
    
    
    return YES;
    
    // 6 
}


- (void)mutable1
{
    for (int i = 0; i < 10; i ++){
        NSLog(@"gggg ");
    }
    
    // 多線程執行完之後,會到主線程
    // 比如 請求完網絡數據後,刷新ui界面(主線程)
    [self performSelectorOnMainThread:@selector(mainThred) withObject:nil waitUntilDone:NO];
}

- (void)mainThread
{
    for (int i = 0; i < 100; i ++){
        NSLog(@"mainThred");
    }
}



 //GCD
    //創建一個隊列
    dispatch_queue_t queue = dispatch_queue_create("test", nil);
    //異步多線程
    dispatch_async(queue, ^{
        for (int i = 0; i < 100; i ++){
            NSLog(@"多線程 thread %i ", i);
        }
        BOOL isMuliti = [NSThread isMultiThreaded];
        if (isMuliti){
            NSLog(@"多線程");
        }
        //執行完成之後,回到主線程
        dispatch_sync(dispatch_get_main_queue(), ^{
            BOOL isMain = [NSThread isMainThread];
            if (isMain){
                NSLog(@"主線程");
            }
        });
    });
    
    // 同步運行在當前線程
    dispatch_sync(queue, ^{});
    
    for (int i = 0; i < 100; i ++){
        NSLog(@"main thread %i ", i);
    }
    


eg異步加載數據


#import <UIKit/UIKit.h>

@interface UIImageView (WebCatch)
- (void)setImageWithURL:(NSURL *)url;
@end


#import "UIImageView+WebCatch.h"

@implementation UIImageView (WebCatch)

- (void)setImageWithURL:(NSURL *)url
{
    dispatch_queue_t queue = dispatch_queue_create("loadImage", nil);
    dispatch_async(queue, ^{
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        //UI的操作主要放在主線程上去處理
        dispatch_async(dispatch_get_main_queue(), ^{
            self.image = image;
        });
    });
}

@end

#import "ViewController.h"
#import "UIImageView+WebCatch.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadView
{
    [super loadView];
    for (int i = 0; i < 10; i ++){
        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, i * 50, 50, 50)];
        [imageview setImageWithURL:[NSURL URLWithString:@"http://a.hiphotos.baidu.com/image/w%3D2048/sign=0ef89c67cf1b9d168ac79d61c7e6b58f/a71ea8d3fd1f4134ef340bc6241f95cad1c85e02.jpg"]];
        [self.view addSubview:imageview];
        [imageview release];
    }
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 100, 80, 40);
    [button setTitle:@"button" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(onclick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)onclick
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"title" message:@"iii" delegate:self cancelButtonTitle:@"okay" otherButtonTitles: nil];
    [alert show];
    [alert release];
}
@end

NSRunLoop

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
//    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
//    self.window.rootViewController = self.viewController;
   
    //開啓一個線程
    [self performSelectorInBackground:@selector(multithread) withObject:nil];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)multithread
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    //默認添加到了runloop裏面
//    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    //沒有添加到runloop中,需手動添加
    NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    //添加到runloop中
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [pool release];
    [[NSRunLoop currentRunLoop] run];
    NSLog(@"線程over");
}

- (void)timerAction
{
    NSLog(@"time out");
}



發佈了65 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章