NSThread_多线程开发 NSOperation 自带地图应用_路径导航 NSThread


//NSThread_多线程开发
#import "ViewController.h"
#define ROW 5
#define COLUMN 3
#define IMAGE_COUNT ROW*COLUMN
#define WIDTH 100//图片宽
#define HEIGHT WIDTH//图片高

@interface ViewController ()
{
    NSMutableArray *_imageViews;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self layout];
}

- (void)layout
{
    _imageViews = [NSMutableArray array];
    for (int r = 0; r < COLUMN; r++) {
        for (int c = 0; c < ROW; c++) {
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(18.75 + r * 118.75, 20 + c * 118.75, WIDTH, HEIGHT)];
            imageView.backgroundColor = [UIColor orangeColor];
            [self.view addSubview:imageView];
            [_imageViews addObject:imageView];
        }
    }
    
    //添加按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(50, 500,275,30);
    [button setTitle:@"加载图片" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(useMultiThread) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)updateImage : (NSArray *)arr
{
    UIImage *image = [UIImage imageWithData:arr[0]];
    UIImageView *imageView = _imageViews[[arr[1] intValue]];
    imageView.image = image;
}

- (void)loadImage : (NSNumber *)index{
        NSLog(@"%@", [NSThread currentThread].name);
    if (![index isEqual:@14]) {
        //如果当前进程不是最后一个,就休眠2秒
        [NSThread sleepForTimeInterval:2];
    }
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://i1.s2.dpfile.com/2009-12-16/3351675_b.jpg(700x700)/thumb.jpg"]];
    NSArray *arrData = @[data,index];
    [self performSelectorOnMainThread:@selector(updateImage:) withObject:arrData waitUntilDone:YES];
}

//- (void)useMultiThread
//{
//    for (int i = 0; i < IMAGE_COUNT; i++) {
//        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]];
//        thread.name = [NSString stringWithFormat:@"我的线程:%d",i];
//        [thread start];//启动
//    }
//}


#pragma mark 改变线程优先级
//提高他被优先加载的几率,但是他也未必就第一个加载。1,其他进程是先启动的 2.网络状态我们没有办法修改
- (void)useMultiThread{
NSMutableArray *threads = [NSMutableArray array];
for(int i = 0; i < IMAGE_COUNT ; i++){
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]];
    //设置优先级
    if (i ==IMAGE_COUNT - 1){
        thread.threadPriority = 1.0;
    }
    else{
        thread.threadPriority = 0;
    }


    [threads addObject:thread];
}
    
    
    for (int i  = 0; i < IMAGE_COUNT; i++) {
        NSThread *thread = threads[i];
        [thread start];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end







//
//  ViewController.m
//  NSOperation
//
//  Created by DC020 on 15/12/24.
//  Copyright (c) 2015年 Bill. All rights reserved.
//

#import "ViewController.h"
#define ROW 3
#define COLUMN 5
#define imageCount ROW*COLUMN
#define WIDTH 100
#define HEIGHT WIDTH
@interface ViewController ()
{
    NSMutableArray *_imageViews;
}
@end
    
@implementation ViewController
    
- (void)viewDidLoad {
    [super viewDidLoad];
    [self layout];
}
-(void)layout{
    _imageViews = [NSMutableArray array];
    for (int c = 0; c < COLUMN; c++) {
        for (int r = 0; r<ROW; r++) {
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(18.75+r*118.75, 20+c*118.75, WIDTH, HEIGHT)];
            image.backgroundColor = [UIColor redColor];
            [self.view addSubview:image];
            [_imageViews addObject:image];
            }
        }
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(50, 500, 275, 30)];
    [button setTitle:@"加载图片" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(userMultiThread) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    }



-(void)updateImage:(NSArray *)arr{
    UIImage *image = [UIImage imageWithData:arr[0]];
    UIImageView *imageView = _imageViews[[arr[1] intValue]];
    imageView.image = image;
    }



-(void)loadImage:(NSNumber *)index{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://b.zol-img.com.cn/desk/bizhi/image/7/2560x1600/1447404575613.jpg"]];
    
    //更新UI界面,调用主线程队列
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [self updateImage:@[data,index]];
    }];
    }




-(void)userMultiThread{
    //1.创建一个操作队列
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];
    operationQueue.maxConcurrentOperationCount = 5;//设置最大并发线程数;
    //2.向队列添加操作
//    for(int i = 0;i < imageCount; i++){
        //方法1.创建操作块,添加到队列
//        NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
//            [self loadImage:[NSNumber numberWithInt:i]];
//        }];
//        //向操作队列 添加 操作
//        [operationQueue addOperation:blockOperation];
        
        
        
        //方法2:祷文invocation
//        NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]];
//        [operationQueue addOperation:invocationOperation];
        
        
        //方法3:控制线程的执行顺序
        NSBlockOperation *lastOp = [NSBlockOperation blockOperationWithBlock:^{
            [self loadImage:@(imageCount - 1)];
        }];
        for (int j = 0; j < imageCount-1; j++) {
            NSBlockOperation *normalOp = [NSBlockOperation blockOperationWithBlock:^{
                [self loadImage:[NSNumber numberWithInt:j]];
            }];
            //设置依赖操作(普通依赖最后)
            [normalOp addDependency:lastOp];
            [operationQueue addOperation:normalOp];
        }
    [operationQueue addOperation:lastOp];
    }
//}

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

@end



//
//  ViewController.m
//  自带地图应用_路径导航
//
//  Created by DC020 on 15/12/24.
//  Copyright (c) 2015年 Bill. All rights reserved.
//

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
@interface ViewController (){
    CLGeocoder *_geocoder;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _geocoder = [[CLGeocoder alloc]init];
    [self drawRoute];
}

-(void)drawRoute{
    //根据“西安”进行地理编码
    [_geocoder geocodeAddressString:@"西安市" completionHandler:^(NSArray *placemarks, NSError *error) {
        //定位地标
        CLPlacemark *clPlacemark1 = [placemarks firstObject];//一般来说第一个是关联度最高的
        //定位地标转化为地图地标
        MKPlacemark *mkPlacemark1 = [[MKPlacemark alloc]initWithPlacemark:clPlacemark1];
        //注意:地理编码一次只能定位到一个位置
     [_geocoder geocodeAddressString:@"哈尔滨市" completionHandler:^(NSArray *placemarks, NSError *error) {
         CLPlacemark *clPlacemark2 = [placemarks firstObject];
         MKPlacemark *mkplacemark2 = [[MKPlacemark alloc]initWithPlacemark:clPlacemark2];
         //配置地图设置信息
         NSDictionary *options =@{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard),MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving};//将其转化成对象类型(加括号的意思)
         //将地标转化成地图上的“点”
         MKMapItem *mapItem1 = [[MKMapItem alloc]initWithPlacemark:mkPlacemark1];
         MKMapItem *mapItem2 = [[MKMapItem alloc]initWithPlacemark:mkplacemark2];
         //加载地图(点,设置的选项)
         [MKMapItem openMapsWithItems:@[mapItem1,mapItem2] launchOptions:options];
     }];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


//
//  ViewController.m
//  NSThread
//
//  Created by DC020 on 15/12/24.
//  Copyright (c) 2015年 Bill. All rights reserved.
//

#import "ViewController.h"

@interface ViewController (){
    //用于显示图片
    UIImageView *_imageView;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layout];
}
-(void)layout{
    _imageView = [[UIImageView alloc]initWithFrame:[[UIScreen mainScreen]bounds] ];
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:_imageView];
    //下载按钮
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(50, 500, 275, 30)];
    [button setTitle:@"加载图片" forState:UIControlStateNormal];
    [button addTarget:self  action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [self.view addSubview:button];
}
-(void)noNSThread{
    //在资源下载加载的过程中,由于网络原因,有时候我们是很难保证下载时间的,如果不使用多线程可能用户完成一个下载操作需要很长时间的等待,而且在这个过程中无法进行其他操作。->阻塞
    UIImage *image = [[UIImage alloc]initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: @"http://i-7.vcimg.com/trim/867a1fe997bf3baeebbd223ae9aecdc8142598/trim.jpg"]]];
    _imageView.image = image;
}
-(void)updateImageView:(NSData *) imageData{
    UIImage *image = [UIImage imageWithData:imageData];
    _imageView.image = image;
}




-(void)loadImage{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://i-7.vcimg.com/trim/867a1fe997bf3baeebbd223ae9aecdc8142598/trim.jpg"]];
    
    //注意只能在主线程上才能更新UI
    //performSelectorOnMainThread是NSObject一个方法,每一个NSObject都有这个方法
    [self performSelectorOnMainThread:@selector(updateImageView:) withObject:data waitUntilDone:YES];
}

#pragma  mark 多线程下载图片
-(void)loadImageWithMultiThread{
    //方法1:使用对象方法
    //创建一个线程
//    NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(loadImage) object:nil];
//    [thread1 start];//启动一个线程,启动一个线程并不代表立即执行,而是出于就绪状态,当系统调度时才真正执行
    
    //方法2:使用类方法
    [NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

你可能感兴趣的:(NSThread_多线程开发 NSOperation 自带地图应用_路径导航 NSThread)