NSTimer的作用就是以一定的時間間隔向目標對象發送特殊的消息。最常見的是用來控制下載進度條的顯示。
創建一個 Timer
啟動 Timer
停止 Timer
Timer設置
有碼有真相:
//
// AppDelegate.m
// TimerDemo
//
// Created by 李振傑 on 13-12-18.
// Copyright (c) 2013年 swplzj. All rights reserved.
//
#import "AppDelegate.h"
//最大下載時間
#define DOWNLOAD_TIMEOUT 60.0
static int sec = 0;
@interface AppDelegate ()
{
NSTimer *_timer;
}
@end
@implementation AppDelegate
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (void)initView
{
//創建一個進度條:用於顯示下載的進度
UIProgressView *progress = [[UIProgressView alloc] initWithFrame:CGRectMake(20, 60, 220, 30)];
[progress setBackgroundColor:[UIColor brownColor]];
[progress setProgressViewStyle:UIProgressViewStyleBar];
[progress setProgress:0];
[progress setTag:0x123];
[self.window addSubview:progress];
}
//更新進度條
- (void)updateView
{
sec++;
UIProgressView *pro = (UIProgressView *)[self.window viewWithTag:0x123];
if (pro) {
[pro setProgress:sec / DOWNLOAD_TIMEOUT animated:YES];
}
if (sec > DOWNLOAD_TIMEOUT) {
//這是唯一的方法:從NSRunLoop中移除創建的定時器
[_timer invalidate];
_timer = nil;
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
[self initView];
//在當前的runloop中添加一個定時器,每0.5s調用updateView函數一次
_timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateView) userInfo:nil repeats:YES];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
@end