您的位置:首页 > 移动开发 > IOS开发

iOS 线程

2015-06-26 19:29 507 查看
//
//  NetWorkViewController.m
//  AppUI组件学习
//
//  Created by 麦子 on 15/6/19.
//  Copyright (c) 2015年 麦子. All rights reserved.
//

#import "NetWorkViewController.h"

@interface NetWorkViewController ()

@end

@implementation NetWorkViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"网络和多线程";
[self createView];
}

- (void)createView{

UIButton *but = [UIButton buttonWithType:UIButtonTypeRoundedRect];
but.frame = CGRectMake(120, 180, 100, 80);
[but setTitle:@"NSThread" forState:UIControlStateNormal];
but.backgroundColor = [UIColor orangeColor];
but.tag = 1;
[but addTarget:self action:@selector(butClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:but];

UIButton *butA = [UIButton buttonWithType:UIButtonTypeRoundedRect];
butA.frame = CGRectMake(120, 280, 100, 80);
[butA setTitle:@"NSOperation" forState:UIControlStateNormal];
butA.backgroundColor = [UIColor orangeColor];
butA.tag = 2;
[butA addTarget:self action:@selector(butClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:butA];

UIButton *butB = [UIButton buttonWithType:UIButtonTypeRoundedRect];
butB.frame = CGRectMake(120, 380, 100, 80);
[butB setTitle:@"GCD" forState:UIControlStateNormal];
butB.backgroundColor = [UIColor orangeColor];
butB.tag = 3;
[butB addTarget:self action:@selector(butClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:butB];

}

- (void)butClick:(UIButton *)but{

switch (but.tag) {
case 1:{
//            [NSThread detachNewThreadSelector:@selector(myThread:) toTarget:self withObject:nil];

[NSThread currentThread].name = @"主线程";

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(myThread:) object:nil];
thread.name = @"我的线程";
[thread start];
NSLog(@"mainName----%@",[NSThread currentThread].name);
break;
}
case 2:{
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(myThread:) object:@"me !"];

// 尽量用这个
NSOperationQueue *qu = [[NSOperationQueue alloc] init];
[qu addOperation:op];//队列里面的是另外一条线程执行,它就是相当于线程池

//            [op start];// 这种形式怎么是主线程
break;
}
case 3:{
// 会发现其中的线程编号有一样的,其实他的里面也是一个线程池。一般都是用这个方法处理。
dispatch_async(dispatch_get_global_queue(0, 0), ^{

NSLog(@"%@",[NSThread currentThread]);

// 回到主队列,修改UI
dispatch_async(dispatch_get_main_queue(), ^{
UIButton *btn = (UIButton *)[self.view viewWithTag:3];
[btn setTitle:@"线程和主现场通信" forState:UIControlStateNormal];
});

});
break;
}
default:
break;
}

}

-(void)myThread:(id)object {
[NSThread sleepForTimeInterval:2];
NSLog(@"线程开始---%@",[NSThread currentThread].name);
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息