我开始为iPhone开发,因此我在网上看了不同的教程,也try 了一些不同的东西.目前,我正在try 创建一个倒计时,直到午夜.为了得到小时、分钟和秒数,我做了以下操作(我在某处找到了):

NSDate* now = [NSDate date];

int hour = 23 - [[now dateWithCalendarFormat:nil timeZone:nil] hourOfDay];
int min = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] minuteOfHour];
int sec = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] secondOfMinute];
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, min,sec];

然而,我使用-dateWithCalendarFormat:timeZone:的每个地方都会出现以下错误:

warning: 'NSDate' may not respond to '-dateWithCalendarFormat:timeZone:'
(Messages without a matching method signature will be assumed to return 'id' and accept '...' as arguments.)
warning: no '-hourOfDay' method found
error: invalid operands to binary - (have 'int' and 'id')

这看起来很简单.我错过了什么?

此外,我注意到在不同的地方和不同的时间,星号(*)位于时间NSDate* now之后或变量NSDate *now之前.这两者有什么区别?为什么要使用其中一个?

推荐答案

您必须使用以下各项:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit  | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:yourDateHere];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];

NSDate*now和NSDate*now之间没有区别,只是偏好的问题.从编译器的Angular 来看,没有任何变化.

Objective-c相关问答推荐

iOS 7 表格视图无法自动调整内容插入

Objective-C - 将浮点数转换为字符串的其他方法

iPhone SDK 网络连接检测

目标 C:在不离开应用程序的情况下发送Electron邮件

如何使用 Cocoa 创建临时文件?

在 Objective-C 中访问命令行参数

动态转发: suppress Incomplete Implementation 警告

[Facebook-iOS-SDK 4.0]如何从FBSDKProfile获取用户邮箱

你如何安排一个块在下一次运行循环迭代中运行?

使用 UIView animateWithDuration 进行动画处理时无法 UIButton

在 Objective-C/cocoa 中创建文件夹/目录

对块进行类型定义是如何工作的

委托如何在 Objective-C 中工作?

UIWebView didFinishLoading 多次触发

如何在 Cocoa 中获取 NSArray 的第一个 x 元素?

如何在 UITextField 上自动打开键盘?

iPhone如何在打字时获取UITextField的文本?

如何检测父视图控制器中模态视图控制器的解除?

Facebook SDK 登录永远不会在 iOS 9 上回调我的应用程序

如何将按钮放在不会在 iOS 中随表格滚动的 UITableView 上