【问题标题】:No visible @interface for 'NSDate' declares the selector 'initWithString:' [duplicate]'NSDate'没有可见的@interface声明选择器'initWithString:'[重复]
【发布时间】:2013-02-05 07:57:42
【问题描述】:

可能重复:
NSDate initWithString

我写了下面这行代码:

[[NSDate alloc] initWithString:@"2013-03-24 10:45:32 +0200"];

当我尝试编译时,我收到以下错误消息:

ARC 语义问题: 'NSDate' 没有可见的@interface 声明选择器'initWithString:'

项目中有以下内容:

#import <Foundation/Foundation.h>

为了确保包含该类,我尝试了以下行,编译时没有问题:

[[NSDate alloc] init];

我的代码有什么问题?

XCode 4.6 版。
项目 iOS 6.1 中的基础 SDK。

【问题讨论】:

标签: ios objective-c xcode


【解决方案1】:

iOS 平台的 NSDate 类中不存在 initWithString 函数,因为您需要首先使用 NSDateFormatter 指定日期格式化程序,它将日期和时间的文本表示形式转换为 NSDate 对象。使用这样的东西:

NSString *currentDateString = @"2013-03-24 10:45:32";
NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
[dateFormater setDateFormat:@"yyyy-MM-DD HH:mm:ss"];
NSDate *currentDate = [dateFormater dateFromString:currentDateString];

【讨论】:

  • developer.apple.com/library/mac/#documentation/Cocoa/Reference/… 类有方法。但似乎我错过了仅在 OS X 上,而不是在 iOS 上......
  • 更准确地说,initWithString: 方法不适用于 iOS 平台上的 NSDate。在 Mac OS X 平台上,有一个 initWithString: 方法可用。
  • 感谢@dreamlax,编辑了我的答案
  • yyyy-MM-DD 到 yyyy-MM-dd
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-27
相关资源
最近更新 更多