gpt4 book ai didi

iphone - 将 NSTimeInterval 持续时间转换为 NSString

转载 作者:搜寻专家 更新时间:2023-10-30 19:53:42 26 4
gpt4 key购买 nike

我是 iPhone 开发的新手。我有一个问题。我想在 NSString 中转换一个 NSTimeInterval 值,但没有成功。请快速查看以下代码。

在 .h 中

NSTimeInterval startTime;
NSTimeInterval stopTime;
NSTimeInterval duration;

.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];

然后在一个标签上设置这个字符串----

[timeLabel setText:time];

但它不起作用,它显示错误:'stringFromDate:' 的参数 1 的类型不兼容

如果我评论该行,它会在控制台窗口中显示正确的持续时间。

感谢您的帮助。

最佳答案

来自NSDateFormatter class reference :

- (NSString *)stringFromDate:(NSDate *)date
^^^^^^^^ the type of the argument

来自您的代码:

NSTimeInterval duration; 
^^^^^^^^^^^^^^ the type of what you are passing.

错误显示“类型不兼容”。你认为这意味着什么?也许 NSTimeInterval 与 NSDate* 不兼容。以下是文档中关于 NSTimeInterval 的内容:

typedef double NSTimeInterval;

NSTimeInterval is always specified in seconds...

错误告诉您编译器无法将 NSTimeInterval(实际上是 double 值)转换为指向 NSDate 的指针。这真的不足为奇。由于 NSTimeInterval 实际上是一个 double 值,您可以使用 %f 格式说明符轻松地将其转换为字符串。

foo = [NSString stringWithFormat: @"%f", timeInterval];

关于iphone - 将 NSTimeInterval 持续时间转换为 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4041481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com