ios에서 타이머 기능을 추가해야 하며,


구현하기 위한 방법들을 검색한다





상세구현내용


1. 타이머 동작함수를 아래와 같이 작성합니다. labelTimer의 텍스트가 0부터, +1씩 올라가게 합니다. 

-(void)timerMethod:(NSTimer*)thetimer {

    static int i;

    labelTimer.text = [[NSString allocinitWithFormat:@"%d",(int)i];

    i ++;

}


2. 타이머 시작함수 입니다. 여기서 타이머 동작 시간(아래에서는 0.1초 단위로 timerMethod 함수를 불러와서 반영합니다.

-(IBAction)startTimer {

    timer = [NSTimer scheduledTimerWithTimeInterval:0.1

                                             target:self

                                           selector:@selector(timerMethod:)

                                           userInfo:nil

                                            repeats:YES];    

}


3. 타이머가 실행중인지 확인해서 실행중이면 타이머를 종료합니다.

-(IBAction)stopTimer {

    if(nil != timer) {

        [timer invalidate];

        timer = nil;

    }

}




상세구현내용


- (id)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        _timer = [NSTimer    timerWithTimeInterval:0.5 target:self selector:@selector(timerFireMethod:) 
                                      userInfo:nil repeats:YES];
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addTimer:_timer forMode:NSDefaultRunLoopMode];
    }
    return self;
}

- (void)timerFireMethod:(NSTimer*)theTimer {
    NSLog(@"타이머가 호출되었습니다.");
}





상세구현내용 


@interface RecordViewController : UIViewController<AVAudioRecorderDelegate> {


    // 녹음 시간을 화면에 표시하는 레벨에 대한 참조 변수

    IBOutlet UILabel *recordTimeDisplay;


}



// 녹음 시작/멈춤 버튼 클릭시 발생하는 이벤트 함수

- (IBAction)audioRecordingButtonClick {


        timer = [NSTimer scheduledTimerWithTimeInterval:0.03f target:self selector:@selector(timerFired)userInfo:nil repeats:YES];


}


각 셀이 생성될 때마다,

다음 부분이 추가되어야 하는거고,

셀에 버튼을 추가해주고, 이벤트를 걸어둔 것처럼 똑같은 방법으로 진행해야 할듯 




// 타이머 콜백함수

- (void)timerFired {


    // 녹음된 시간을 화면에 갱신합니다.

    recordTimeDisplay.text = [NSString stringWithFormat:@"%@", [self getStringRecordTime:self.pAudioRecorder.currentTime]];


}



셀에 있는 레이블 값을, 숫자로 변형시켜 time값으로 가지고 있는다

그 값으로 아래 함수 구조로 계산하는 방법




- (NSString *)getStringRecordTime:(int)time {

    int secs = time % 60;

    int min = (time % 3600) / 60;

    int hour = (time / 3600);

    

    return [NSString stringWithFormat:@"%02d:%02d:%02d", hour, min, secs];

}





scheduledTimerWithTimeInterval(...)를 호출할 때 아마 self를 target:의 인자로 전달할 것이다. 이는 self가 유지될 것이고 타이머를 무효화할 때까지 절대 소멸되지 않음을 의미한다. 이 작업은 deinit 구현체에서 할 수 없다. 왜냐하면 타이머가 invalidate 메시지가 전달되지 않아 deinit은 호출될 수 없기 때문이다


그러므로 invalidate를 타이머에게 보낼 수 있는 적절한 순간을 찾아야 한다. 예를 들어, 다음과 같이 viewWillAppear: 와 viewDidDisappear:에서 이 작업을 수행함으로써 타이머의 생성과 무효화에 대한 균형을 유지할 수 있다



- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {

    

    // 타이머를 중지합니다.

    [timer invalidate];

    timer = nil;

}


Posted by 스타켄지니어
,