I'm diving into iOS development and the Objective C language and am building an alarm clock app to become familiar with the SDK and language. I have an NSString
object that represents a time, with the range "1:00 am"
to "12:59 am"
. I need to convert this NSString
into two NSInteger
's that contain the hour value and minute value. As I'm doing this, I'm finding the NSString
manipulation that I'm doing to be extremely laborious and it just feels like sloppy code.
Is there a simple way to extract the hour and minute characters from a NSString
representation of a time value and store their numerical values in two NSInteger
's?
Thanks in advance for all your help! I'm gonna get back to it...
This is the official way, as I know it. It's not pretty:
BUT the string fiddling way of doing it (look for
:
, look for space, ...), may give you more headaches on the long term.If you're building an alarm clock app, you probably will want to look into the
NSDate
andNSDateFormatter
classes, instead of trying to pull all those strings apart into integer types. Also, your time range is a bit weird (maybe a typo?) - don't you want all 24 hours to be available?NSDateFormatter
to convert your string into anNSDate
.[NSCalendar currentCalendar]
to extract various date components (like the hour, minute, etc).In other words:
get the time interval and write it as