2010-08-07 2 views
1

저는 iOS 개발과 Objective C 언어로 뛰어 들고 있으며 SDK와 언어에 익숙해 지도록 알람 시계 앱을 제작하고 있습니다. 범위가 "1:00 am"에서 "12:59 am" 인 시간을 나타내는 NSString 개체가 있습니다. 이 NSString을시 값과 분 값이 포함 된 NSInteger 2 개로 변환해야합니다. 내가이 일을하고있을 때, 나는 극도로 힘든 일을하고 있으며 단지 엉성한 코드처럼 느껴지는 NSString 조작을 찾고있다.시간 값의 NSString 표현을 시간과 분이 포함 된 NSInteger로 변환하려면 어떻게해야합니까?

시간 값의 표현 NSString에서시와 분 문자를 추출하고 숫자 값을 두 개의 NSInteger에 저장하는 간단한 방법이 있습니까?

미리 도움 주셔서 감사합니다. 다시 돌아올거야 ...

+2

로 쓰기 검사 대상에 더 순종하는 방식으로 내부적으로 시간을 나타내는, 단지 당신이로 설명하는 것과 같은 문자열을 생성하는 고려 출력이 될 수 있습니다. –

+0

, Seamus, 조언 주셔서 감사합니다! – BeachRunnerFred

답변

6
NSScanner* timeScanner=[NSScanner scannerWithString:...the time string...]; 
int hours,minutes; 
[timeScanner scanInt:&hours]; 
[timeScanner scanString:@":" intoString:nil]; //jump over : 
[timeScanner scanInt:&minutes]; 

NSLog(@"hours:%d minutes:%d",hours,minutes); 
+1

iOS 개발에서 6 년이되었고, 방금 NSScanner를 발견했습니다. 굉장히 유용하다! – Martin

1

알람 시계 앱을 제작하는 경우 모든 문자열을 정수 유형으로 분리하려고 시도하는 대신 NSDateNSDateFormatter 클래스를 조사하는 것이 좋습니다 . 또한 시간 범위가 다소 이상합니다 (오타가있을 수 있습니다). 24 시간 내내 사용 가능하지 않습니까?

+0

감사합니다, 칼, 오타되었습니다;) – BeachRunnerFred

3
  1. 문자열을 NSDate으로 변환하려면 NSDateFormatter을 사용하십시오.
  2. [NSCalendar currentCalendar]에서 extract까지 다양한 date components (시, 분 등)을 사용하십시오. 즉

:

NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"h:m a"]; 
NSDate *date = [formatter dateFromString:@"12:59 pm"]; 
[formatter release]; 

NSDateComponents * components = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date]; 
NSLog(@"hour: %d", [components hour]); 
NSLog(@"minute: %d", [components minute]); 
2

내가 알고있는이, 공식적인 방법입니다. 그것은 꽤 아니다 :

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc]init] autorelease]; 
[dateFormatter setDateFormat:@"h:m a"]; 
NSDate *date = [dateFormatter dateFromString:@"12:34 am"]; 

[dateFormatter setDateFormat:@"h"]; 
NSString *hours = [dateFormatter stringFromDate:date]; 

[dateFormatter setDateFormat:@"m"]; 
NSString *minutes = [dateFormatter stringFromDate:date]; 

하지만 당신에게 장기적으로 더 많은 두통을 줄 수 있습니다 (..., 공간을 찾아, : 확인) 그 일의 문자열 하구 방법.

2
NSString *time = @"1:00 am"; 
NSString *removeam = [time stringByReplacingOccurencesOfString:@" am" withString:@""]; 
SString *removepm = [removeam stringByReplacingOccurencesOfString:@" pm" withString:@""]; 
NSArray *timeArray = [removepm componentsSeparatedByString:@":"]; 
NSInteger *hour = [[timeArray objectAtIndex:0] intValue]; 
NSInteger *mins = [[timeArray objectAtIndex:1] intValue]; 
+0

덕분에, 저는 실제로 당신의 예제에서 문자열 조작에 대해 많은 것을 배웠습니다! – BeachRunnerFred

1

하면 시간 간격을 얻을

duration.text = [NSString stringWithFormat:@"%d:%02d", (int)audioPlayer.duration/60, (int)audioPlayer.duration % 60, nil]; 
관련 문제