【问题标题】:Swift2: String to date, format it and back to string. Found nilSwift2:字符串到日期,格式化并返回字符串。找不到
【发布时间】:2016-02-08 16:23:38
【问题描述】:

我有一个日期字符串:Sun, 07 Feb 2016 21:16:21 +0000

并且需要它:dd.MM.yyyy

以下方法抛出fatal error: nil

if parsedElement == "date" {
    if currentArticle.date.isEmpty {

        let dateFormatter = NSDateFormatter()

        dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
        let tempDate = dateFormatter.dateFromString(str)
        dateFormatter.dateFormat = "dd.MM.yyyy"
        let convertedDate = dateFormatter.stringFromDate(tempDate!)

        currentArticle.date = convertedDate

    }
}

调试:

str String "2016 年 2 月 7 日星期日 21:16:21 +0000"

tempDate NSDate? 2016-02-07 21:16:21 UTC 0xe41bc67eba500000​

convertedDate 字符串“07.02.2016”

看起来不错,但在我发布“currentArticle.date = convertedDate”的那一刻,它会显示convertedDate​ = nil

想法?

PS:currentArticle.date == isEmpty

编辑: if 循环运行 5 次。 如果我给currentArticle.date = str(只有日期字符串),这就是调试器所说的:

1. str String "Sun, 07 Feb 2016 21:16:21 +0000"

2. str ""

3. str String "Thu, 04 Feb 2016 21:18:34 +0000"

4. str ""

5. str String "Thu, 04 Feb 2016 18:57:14 +0000"

【问题讨论】:

  • 'release "currentArticle.date = convertDate"​'是什么意思?
  • 发布我的意思是“继续执行程序”。
  • convertedDate 它是一个字符串。什么是 currentArticle.date 属性类型 String 或 NSDate ?
  • 好的,所以你说的是用断点在该行停止它?然后继续执行程序? convertDate 是一个局部常量,一旦你离开if currentArticle.date.isEmpty 块,convertedDate 将不再存在,这是意料之中的。
  • 就像在我的编辑中发布的一样,我尝试在没有日期格式化程序的情况下运行该方法。有 3 个“parsedElement”。 3 日期字符串。我的方法第一次使用日期格式化程序运行时,很好。但是第二个循环,“if currentArticle.date.isEmpty”!= isEmpty。我不明白,为什么这会导致异常。循环是否应该跳过这一轮并继续第三轮,其中 currentArticle.date 再次为空?

标签: ios string swift date formatter


【解决方案1】:

您遇到了致命错误:

在展开可选值时意外发现 nil -> tempDate

我假设您在该行中遇到此错误:

let convertedDate = dateFormatter.stringFromDate(tempDate!)

这是因为你强制解开一个等于 nil 的可选项。您应该使用可选绑定来打开它,即:

if let tempDate = tempDate {
    let convertedDate = dateFormatter.stringFromDate(tempDate)
    currentArticle.date = convertedDate
}

现在,为什么您的日期格式化程序在这种情况下没有返回 str 的值的问题完全与您的数据有关。您可以在上述可选绑定代码块中添加else,以在这种情况下显示str,以缩小问题范围。

【讨论】:

  • 非常感谢。它工作得很好。当然,感谢您不仅向我展示了代码,还向我解释了它。我确定我明白了。非常感谢。
猜你喜欢
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2018-07-31
  • 2023-04-07
  • 2014-05-20
相关资源
最近更新 更多