/*
1. NSThread
1> 类方法 detachNewThreadSelector
直接启动线程,调用选择器方法
2> 实例方法 initWithTarget
需要使用start方法,才能启动实例化的线程
优点:简单
缺点:控制线程的生命周期非常困难
控制并发线程数困难
控制线程的先后执行顺序困难
列如:下载图片(后台线程) ->滤镜美化(后台线程) -> 更新UI(主线程)
*/
#define SCREENWIDTH [UIScreen mainScreen].bounds.size.width
#define SCREENHEIGHT [UIScreen mainScreen].bounds.size.height
#define W SCREENWIDTH/4
#define H (SCREENHEIGHT-50)/7
#define RANDOMDATA (float)arc4random_uniform(256)/255
#import "ViewController.h"
@interface ViewController ()
{
NSSet *viewSet;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setSubview];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)setSubview
{
//实例化视图集合
NSMutableSet *myViewSet = [NSMutableSet setWithCapacity:28];
for (int row = 0; row < 7; row++) {
for (int col = 0; col < 4; col++) {
//计算view的位置
int x = col * W;
int y = row * H;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, W, H)];
view.backgroundColor = [UIColor colorWithRed:RANDOMDATA green:RANDOMDATA blue:RANDOMDATA alpha:1];
[self.view addSubview:view];
[myViewSet addObject:view];
}
}
viewSet = myViewSet;
//添加按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(0, SCREENHEIGHT-50, SCREENWIDTH, 50)];
[button setBackgroundColor:[UIColor blackColor]];
[button setTitle:@"刷新图片" forState:UIControlStateNormal];
[button addTarget:self action:@selector(didButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
#pragma mark - 多线程:NSThread加载图片
- (IBAction)didButtonClicked:(id)sender
{
NSLog(@"点击我!");
[self threadLoadColorView];
}
- (void)threadLoadColorView
{
//多线程一定要加入到自动释放池中
@autoreleasepool {
for (UIView *colorView in viewSet) {
//类方法,直接新建线程调用detachNewThreadSelector方法
[NSThread detachNewThreadSelector:@selector(loadColorView:) toTarget:self withObject:colorView];
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadColorView:) object:colorView];
//启动线程
[thread start];
}
}
}
- (void)loadColorView:(UIView *)view
{
NSLog(@"%@",[NSThread currentThread]);
[NSThread sleepForTimeInterval:1];
//在主线程中gengxinUI
[view performSelectorOnMainThread:@selector(setBackgroundColor:) withObject:[UIColor colorWithRed:RANDOMDATA green:RANDOMDATA blue:RANDOMDATA alpha:1] waitUntilDone:NO];
// view.backgroundColor = [UIColor colorWithRed:RANDOMDATA green:RANDOMDATA blue:RANDOMDATA alpha:1];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end