I would do it something like this:
int totalSeconds = (int)streamer.progress; hours = totalSeconds / (60 * 60); minutes = (totalSeconds / 60) % 60; seconds = totalSeconds % 60; if ( hours > 0 ) { formattedTimeString = [NSString stringWithFormat:@"%d:%02d:%02d", hours, minutes, seconds]; } else { formattedTimeString = [NSString stringWithFormat:@"%d:%02d", minutes, seconds]; }
Now, in the end, formattedTimeString is the desired time, but you do not “own” it - you must save it or save it in the “copy” property if you want to save it.
Note that% 02d gives you two digits, the zero filled number, which is usually required for numbers several times.
To see how you do it with stringByAppendingFormat, it will look something like this:
NSString* formattedTimeString = @""; if ( hours > 0 ) { formattedTimeString = [formattedTimeString stringByAppendingFormat:@"%d:", hours]; } formattedTimeString = [formattedTimeString stringByAppendingFormat:@"%d:%02d", minutes, seconds];
However, in this case, you will get a time similar to 3: 4: 05, more than the more desirable 3:04:05.
Please note that formattedTimeString is overwritten every time, but it’s OK because you don’t “own” it at any time, so you are responsible for releasing it.
Finally, to see it with a mutable string, it might look like this:
NSMutableString* formattedTimeString = [NSMutableString string]; if ( hours > 0 ) { [formattedTimeString appendFormat:@"%d:", hours]; } [formattedTimeString appendFormat:@"%d:%02d", minutes, seconds];
Again, the result of the time is an undesirable 3: 4: 05, and again you don't have formattedTimeString at the end, so you need to save it or save it using the copy property to save it.