San*_*ngh 3 iphone objective-c
我是iphone开发的新手.我有一个问题.我想在NSString中转换NSTimeInterval值,但在此不成功.请快速查看下面的代码.
在.h
NSTimeInterval startTime;
NSTimeInterval stopTime;
NSTimeInterval duration;
Run Code Online (Sandbox Code Playgroud)
在.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];
Run Code Online (Sandbox Code Playgroud)
并在一个标签上设置此字符串----
[timeLabel setText:time];
Run Code Online (Sandbox Code Playgroud)
但它不起作用它显示错误:'stringFromDate:'的参数1的不兼容类型
如果我评论该行,它会在控制台窗口中显示正确的持续时间.
谢谢你的帮助.
- (NSString *)stringFromDate:(NSDate *)date
^^^^^^^^ the type of the argument
Run Code Online (Sandbox Code Playgroud)
从您的代码:
NSTimeInterval duration;
^^^^^^^^^^^^^^ the type of what you are passing.
Run Code Online (Sandbox Code Playgroud)
错误显示"不兼容的类型".你觉得这意味着什么?也许NSTimeInterval与NSDate*不兼容.以下是文档对NSTimeInterval的说法:
typedef double NSTimeInterval;
Run Code Online (Sandbox Code Playgroud)
NSTimeInterval始终以秒为单位指定...
该错误告诉您编译器无法将NSTimeInterval(实际上是双精度)转换为指向NSDate的指针.这并不奇怪.由于NSTimeInterval实际上是双精度数,因此可以使用%f格式说明符轻松将其转换为字符串.
foo = [NSString stringWithFormat: @"%f", timeInterval];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14011 次 |
| 最近记录: |