[英]Swift app crashes on real device but works on simulator
This function gets the date from yesterday;此函数获取昨天的日期; it is working on my emulator but it crashes with my real device.
它在我的模拟器上工作,但在我的真实设备上崩溃了。
I am working with Xcode6 Beta 6.我正在使用 Xcode6 Beta 6。
var tuple :(value Int, unit:NSCalendarUnit) = (1, NSCalendarUnit.CalendarUnitDay)
var date = NSDate()
var yesterday = NSCalendar.currentCalender().dateByAddingUnit(tuple.unit, value: (-tuple.value), toDate: date, options: NSCalendarOptions.SearchBackwards)
This is the error I get on my real device:这是我在真实设备上遇到的错误:
-[_NSCopyOnWriteCalendarWrapper dateByAddingUnit:value:toDate:options:]: unrecognized selector sent to instance 0x176cca10
I recently had a similar error.我最近有一个类似的错误。
I suspect you're trying to run the code on a pre 8.0 device.我怀疑您正在尝试在 8.0 之前的设备上运行代码。 If that's the case,
dateByAddingUnit
is not available on your device (see the header)如果是这种情况,则
dateByAddingUnit
在您的设备上不可用(请参阅标题)
@availability(iOS, introduced=8.0)
You can achieve what you're trying to do by using `dateByAddingComponents' - it's a little more cumbersome but should give you the same result.你可以通过使用`dateByAddingComponents'来实现你想要做的事情——它有点麻烦,但应该给你相同的结果。 Try the following playground
试试下面的游乐场
import UIKit
import Foundation
var tuple:( Int, NSCalendarUnit) = (1, NSCalendarUnit.CalendarUnitDay)
var date = NSDate()
/* 8.0+ */
var yesterday = NSCalendar.currentCalendar().dateByAddingUnit(tuple.1, value: (-tuple.0), toDate: date, options: NSCalendarOptions.SearchBackwards)
/* 7.1 + */
let component = NSDateComponents()
if tuple.1 == NSCalendarUnit.CalendarUnitDay {
component.day = -tuple.0
}
var alsoYesterday = NSCalendar.currentCalendar().dateByAddingComponents(component, toDate: date, options: NSCalendarOptions.SearchBackwards)
Hope this helps!希望这可以帮助! :)
:)
When I ran your code it has syntax errors to begin with.当我运行你的代码时,它开始出现语法错误。 I just took the following code and ran it both on a device in playground, in a online simulator and an xcode project and it works for all three.
我只是拿了下面的代码,并在操场上的设备、在线模拟器和 xcode 项目上运行它,它适用于所有三个。
The following works for me.以下对我有用。
http://swiftstub.com/992344166/ Click Run to see result. http://swiftstub.com/992344166/点击运行查看结果。
var date = NSDate()
var yesterday = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -1, toDate: date, options: NSCalendarOptions.SearchBackwards)
println(yesterday)
Please try below code请尝试以下代码
let today = NSDate()
let yesterday = today.dateByAddingTimeInterval(-24 * 60 * 60)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.