您的位置:首页 > 产品设计 > UI/UE

多线程问题 ----- UI视图 & NSTimer 同时执行操作

2014-11-26 13:37 323 查看
//
//  RootViewController.m
//  多线程-
//
//  Created by zm on 14-11-26.
//  Copyright (c) 2014年 practice. All rights reserved.
//

#import "RootViewController.h"

@interface RootViewController ()<NSURLConnectionDataDelegate>
{
UIProgressView *_progressView;
}
@end

@implementation RootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {

}
return self;
}

/**
默认情况下:
*  scrollView  拖动时, NSTimer 暂停线程操作,停止计时
移开鼠标后,继续线程操作,继续计时

*  原因: 事件源有三种(界面触摸,网络,定时器),界面触摸优先级最高
界面触摸事件处理的优先级要高于定时器线程的优先级
*
*/
-(void)prepareScrollView
{
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, 320, 100)];
[self.view addSubview:scrollView];

for (int i = 0; i < 3; i++) {
float x = i*320;
float y = 0;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, 320, 40)];
float radomColor = arc4random()%255/255.0;
UIColor *color = [UIColor colorWithRed:radomColor green:radomColor blue:radomColor alpha:1.0];
view.backgroundColor = color;
[scrollView addSubview:view];
}

scrollView.contentSize = CGSizeMake(320*3, 0);

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(testTimer) userInfo:nil repeats:YES];
[timer fire];

/**
*  scroollview   NSTimer 共存的原理:
两个事件源共用一个 runLoop
修改timer  runLoop 模式,则能共存,互不影响,同时进行
[主线程,UI线程的runloop 模式不可更改!]

*  NSRunLoop 主要有两种模式
NSDefaultRunLoopMode,
*/
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}

-(void)testTimer
{
static int count = 1;
NSLog(@"定时器运行:%d",count);
}

- (void)viewDidLoad
{
[super viewDidLoad];

[self prepareScrollView];

}

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