【问题标题】:Swift 4 - Cannot assign value of type 'NSDate' to type 'Date?' ONLY on Physical DeviceSwift 4 - 无法将“NSDate”类型的值分配给“日期?”仅在物理设备上
【发布时间】:2018-03-12 12:52:15
【问题描述】:

我已经看到与此错误相关的其他问题,但我没有看到任何人提及我目前遇到的情况。请注意,在转换为 Swift 4 之前,我对这段代码没有任何问题。

下面是有问题的代码:

let verseNotification = NSManagedObject(entity: entity, insertInto: self.managedObjectContext) as! VerseNotification
verseNotification.date_scheduled = NSDate(timeIntervalSinceNow: finalTimeToScheduleSinceNow)

注意属性date_scheduled的类型是Date

@NSManaged public var date_scheduled: Date?

当我在物理 iPhone(iPhone 7)上构建我的应用程序以在 DEBUG 中部署时,我收到以下错误(从 Swift 3 转换为 Swift 4 后):

Cannot assign value of type 'NSDate' to type 'Date?' - Insert 'as Date'

按照它说的做可以解决问题...所以,现在我的代码是这样的:

verseNotification.date_scheduled = NSDate(timeIntervalSinceNow: finalTimeToScheduleSinceNow) as Date

...直到我将目标切换到模拟器。当我将目标切换为 Simulator iPhone 7 设备时,我现在收到以下错误:

'NSDate' is not implicitly convertible to 'Date'; did you mean to use 'as' to explicitly convert?

这个错误令人困惑的是,正如您在上面看到的,我明确地转换为Date 类型。具有讽刺意味的是,我可以为 Simulator iPhone 7 消除此错误的唯一方法是删除我在第一步中添加的 as Date

发生了什么事?我错过了什么?

我担心为“通用设备”构建发布版本,不知道为什么会出现冲突错误。

更新 我发现了一些新的非常有趣的东西。

当我构建以部署到我的物理 iPhone 7 设备时,生成的数据模型对象的 Core Data 定义将 date_scheduled 属性创建为 Date

但是,当我构建以部署在 Simulator iPhone 7 上时,生成的数据模型对象的核心日期定义会将 date_scheduled 属性创建为 NSDate。

这是 Swift 4 或 Xcode 9 中的新功能吗?从 Swift 3 转换到 Swift 4 后,我是否缺少新设置?

【问题讨论】:

  • 我认为你应该在swift中使用Date(timeIntervalSinceNow: finalTimeToScheduleSinceNow)而不是NSDate(timeIntervalSinceNow: finalTimeToScheduleSinceNow)
  • @3stud1ant3 - 我试过了,这就是我发现我在“更新”中发布的内容的方式——Core Data 根据我选择的目标设备生成不同的类型。我很困惑。
  • 这里描述并“解决”了这个问题。 stackoverflow.com/questions/46370566/… 显然,Xcode 有错误。

标签: ios core-data swift3 swift4


【解决方案1】:

这是 Xcode 错误。请报告或打开雷达以在将来的版本中修复

【讨论】:

    【解决方案2】:

    以下是我解决此问题的方法(Xcode 9.2、Swift 4.0、watchOS 4):

    #if arch(i386) //watchOS Simulator needs this
        completionDate = newValue as NSDate?
    #else //watchOS device needs this
        completionDate = newValue
    #endif  
    

    在我的例子中,我在我的 iOS 和 watchOS 目标之间共享代码,所以它看起来像这样:

    #if os(watchOS)
        #if arch(i386) //watchOS Simulator needs this
                completionDate = newValue as NSDate?
            #else //watchOS device needs this
                completionDate = newValue
        #endif  
    #else //iOS, simulator or device
            completionDate = newValue
    #endif
    

    在上面,completionDate 是我的核心数据日期属性,newValue 是一个 Swift “日期?”价值。

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多