ios - 无法在 Swift 中将 Anyobject 转换为 NSString

标签 ios swift nsstring

运行时出现异常

self.year = value as! NSString 

异常(exception):

 Could not cast value of type '__NSDate' (0x1051bd6a0) to 'NSString' (0x10564d8e0).

我错过了什么?

var  datePicker = ActionSheetDatePicker(title: "Date:",datePickerMode: UIDatePickerMode.Date, selectedDate: NSDate(),doneBlock: { 

   picker, value, index in

   self.year = value as! NSString 

   println("year = \(year)")
   println("value = \(value)")

   return
   }, cancelBlock: { ActionStringCancelBlock in return }, origin: sender.superview!.superview)

最佳答案

我认为你必须通过你选择的值将日期转换为字符串

let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss"
let dateStr: String = formatter.string(from: value as! Date)

您可以使用任何其他格式,例如:“yyyy”或“HH:mm:ss”等。

并将其设置为您的年份变量

self.year = dateStr

关于ios - 无法在 Swift 中将 Anyobject 转换为 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30442987/

相关文章:

ios - 在没有更多上下文的情况下,表达式类型不明确 - 在 Facebook 包装器中

ios - objective-C : No Matter what I do CIDetector is always nil

swift - 我该如何修复类型 '()' 无法符合 'View' ;只有 struct/enum/class 类型可以符合协议(protocol)

ios - 如何计算字符串在长 NSString 中的次数?

iphone - 当应用程序在 main 中的 EXC_BAD_ACCESS 上崩溃时不会生成崩溃日志

objective-c - 如何在第三方音乐应用程序中获取正在播放的信息?

ios - UIAlertController 默认首字母大写

ios - 在 UITextFieldBeginEditing 上调用 prepare for segue

ios - 不明白为什么我的 NSString 数据为空

ios - Xcode 中的解码和编码