NSThread应用

来源:互联网 发布:ug中心钻编程 编辑:程序博客网 时间:2024/06/06 14:16

在iphone开发中经常需要更新UI的显示,一般需要启动新的线程来运行相关数据地更新,然后在另一线程中更新UI. 这里利用NSThread实现这样一个功能:更新进度条。

//

//  NSThreadDemoAppDelegate.m

//  NSThreadDemo

//

//  Created by Chelsea Wang(420989762/wwssttt@163.com) on 11-10-11.

//  Copyright 2011 __MyCompanyName__. All rights reserved.

//

@implementation NSThreadDemoAppDelegate

float processValue = 0;

@synthesize window = _window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    // Override point for customization after application launch.

    UIProgressView* processView = [[UIProgressViewalloc] initWithProgressViewStyle:UIProgressViewStyleDefault];

    [processView setFrame:CGRectMake(10,50, 200, 30)];

    [processView setTag:101];

    [processView setProgress:0.0];

    

    UILabel* processLabel = [[UILabel alloc]initWithFrame:CGRectMake(225, 30,100, 50)];

    [processLabel setText:[NSString stringWithFormat:@"%.2f%%",processValue*100]];

    [processLabel setTag:102];

    

    

    

    [self.window addSubview:processView];

    [processView release];

    [self.window addSubview:processLabel];

    [processLabel release];

    [self.window makeKeyAndVisible];

    

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

    return YES;

}

-(void)updateProcess{

    NSAutoreleasePool* p = [[NSAutoreleasePoolalloc] init];

    [self performSelectorOnMainThread:@selector(updateUI)withObject:nil waitUntilDone:YES];

    [p release];

}

-(void)updateUI{

    if (processValue <= 1.0) {

        processValue += 0.1;

        

        UIProgressView* processView = (UIProgressView*)[self.windowviewWithTag:101];

        [processView setProgress:processValue];

        

        UILabel* processLabel = (UILabel*)[self.windowviewWithTag:102];

        [processLabel setText:[NSString stringWithFormat:@"%.2f%%",processValue*100]];

        

        [NSTimer scheduledTimerWithTimeInterval:0.5target:self selector:@selector(updateUI)userInfo:nil repeats:NO];

    }else{

        processValue = 0.0;

        [NSTimer scheduledTimerWithTimeInterval:0.5target:self selector:@selector(updateUI)userInfo:nil repeats:NO];

    }

}

原创粉丝点击