Swift app crashes on real device but works on simu

2019-02-27 03:13发布

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.

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

标签: ios swift xcode6
3条回答
smile是对你的礼貌
2楼-- · 2019-02-27 03:50

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.

The following works for me.

http://swiftstub.com/992344166/ Click Run to see result.

var date = NSDate()
var yesterday = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -1, toDate: date, options: NSCalendarOptions.SearchBackwards)
println(yesterday)
查看更多
太酷不给撩
3楼-- · 2019-02-27 04:04

Please try below code

let today = NSDate()
let yesterday = today.dateByAddingTimeInterval(-24 * 60 * 60)
查看更多
你好瞎i
4楼-- · 2019-02-27 04:12

I recently had a similar error.

I suspect you're trying to run the code on a pre 8.0 device. If that's the case, dateByAddingUnit is not available on your device (see the header)

@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. 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! :)

查看更多
登录 后发表回答