NSThread使用

2016-03-24  本文已影响20人  cz3w

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blackColor];

    UIButton * btnStart = [[UIButton alloc]initWithFrame:CGRectMake(20, 20, 300, 40)];

    [btnStart setTitle:@"START" forState:UIControlStateNormal];

    [self.view addSubview:btnStart];

    self.actView = [[ UIActivityIndicatorView alloc]initWithFrame:

                                                                        CGRectMake(200, 100, 50, 50)];

   [self.view addSubview:self.actView];

   self.actView.activityIndicatorViewStyle = 

                                                                UIActivityIndicatorViewStyleWhiteLarge;

   self.actView.hidesWhenStopped = NO;

   [btnStart addTarget:self action:@selector(bigTaskAction) 

                          forControlEvents:UIControlEventTouchUpInside];

   self.aProgressView = [[UIProgressView alloc]initWithFrame:

                                                                          CGRectMake(20, 500, 300, 20)];

   [self.view addSubview:self.aProgressView];

}

-(void)bigTaskAction{

    [self.actView startAnimating];

    [NSThread detachNewThreadSelector:@selector(bigTask) toTarget:self withObject:nil];

//[self bigTask];

}

-(void)bigTask{

  @synchronized(self) {

    int updateUIWhen = 2000;

    for (int i=0; i<50000; i++) {

      NSString * newString =[ NSString stringWithFormat:@"i = %i",i];

      NSLog(@"%@",newString);

      if (i==updateUIWhen) {

          float f = (float)i/50000;

          NSNumber *percentDone = [NSNumber numberWithFloat:f];

          [self performSelectorOnMainThread:

                         @selector(updateProgressViewWithPercentage:) 

                         withObject:percentDone   waitUntilDone:YES];

          updateUIWhen = updateUIWhen +2000;

       }

}

      [self performSelectorOnMainThread:

                         @selector(updateProgressViewWithPercentage:) 

                         withObject:[NSNumber numberWithFloat:1.0] waitUntilDone:YES];

       [self.actView stopAnimating];

  }

}

-(void)updateProgressViewWithPercentage:(NSNumber *)percentDone {

      [self.aProgressView setProgress:[percentDone floatValue] animated:YES];

}

上一篇下一篇

猜你喜欢

热点阅读