sábado, 10 de dezembro de 2011

Função - Formatar horário a partir de X segundos


//  ViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    
    // Criando um processo para chamar o métodos onTimer a cada 1 segundo
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}

- (void)onTimer
{
    static int segundos = 0;
    
    segundos++;
        
    // Imprimi no console o horário formatado
    NSLog(@"%@",[self horarioFormatadaComSegundos:segundos]);
}

// Função para formatar um horário a partir de inteiros.
- (NSString *)horarioFormatadaComSegundos:(int)segundos
{
    int hor = 0, min = 0, seg = 0;
    
    seg = segundos;
    
    while (seg >= 60) { min+=1; seg-=60; }
    
    while (min >= 60) { hor+=1; min-=60; }
    
    NSString * h, * m, * s;
    
    h = (hor > 9) ? [NSString stringWithFormat:@"%d",hor] : [NSString stringWithFormat:@"0%d",hor] ;
    m = (min > 9) ? [NSString stringWithFormat:@"%d",min] : [NSString stringWithFormat:@"0%d",min] ;
    s = (seg > 9) ? [NSString stringWithFormat:@"%d",seg] : [NSString stringWithFormat:@"0%d",seg] ;
    
    return [NSString stringWithFormat:@"%@:%@:%@",h,m,s];
}