关闭

NSThread应用

397人阅读 评论(0) 收藏 举报

在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 = [[UIProgressView alloc] 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 = [[NSAutoreleasePool alloc] init];

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

    [p release];

}

-(void)updateUI{

    if (processValue <= 1.0) {

        processValue += 0.1;

        

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

        [processView setProgress:processValue];

        

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

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

        

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

    }else{

        processValue = 0.0;

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

    }

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:453260次
    • 积分:5977
    • 等级:
    • 排名:第4244名
    • 原创:61篇
    • 转载:592篇
    • 译文:0篇
    • 评论:15条
    最新评论