Reputation: 826
I am new in iphone development. I have a issue. I want to convert a NSTimeInterval value in NSString, but not success in this. please a quick look on below code.
in .h
NSTimeInterval startTime;
NSTimeInterval stopTime;
NSTimeInterval duration;
in .m
startTime = [NSDate timeIntervalSinceReferenceDate];
stopTime = [NSDate timeIntervalSinceReferenceDate];
duration = stopTime-startTime;
NSLog(@"Duration is %@",[NSDate dateWithTimeIntervalSinceReferenceDate: duration]);
NSLog(@"Duration is %@", [NSString stringWithFormat:@"%f", duration]);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *time = [dateFormatter stringFromDate:duration];----> Error
[dateFormatter release];
And on one label set this string----
[timeLabel setText:time];
but it not works it shows error: incompatible type for argument 1 of 'stringFromDate:'
and if i comment that line it shows the right duration in console window.
thanks for any help.
Upvotes: 3
Views: 14502
Reputation: 86651
From the NSDateFormatter class reference:
- (NSString *)stringFromDate:(NSDate *)date
^^^^^^^^ the type of the argument
From your code:
NSTimeInterval duration;
^^^^^^^^^^^^^^ the type of what you are passing.
The error says "incompatible type". What do you think that means? Perhaps NSTimeInterval is not compatible with NSDate*. Here is what the docs say about NSTimeInterval:
typedef double NSTimeInterval;
NSTimeInterval is always specified in seconds...
The error is telling you the compiler can't convert an NSTimeInterval (which is really a double) into a pointer to an NSDate. This is not surprising really. Since an NSTimeInterval is really a double, you can convert it into a string easily by using the %f
format specifier.
foo = [NSString stringWithFormat: @"%f", timeInterval];
Upvotes: 8
Reputation: 18378
NSString *time = [dateFormatter stringFromDate:duration];----> Error
This duration is not class NSDate, so It can not be converted by this method named stringFromDate. As Vladimir said, NSTimeInterval is double, with his method you can get the right NSString.
Upvotes: 0
Reputation: 170839
NSTimeInterval is actually a double, so to convert it to a string you should just use
NSString *time = [NSString stringWithFormat:@"%f", duration];
Upvotes: 3