简体   繁体   中英

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.

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

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)

Please try below code

let today = NSDate()
let yesterday = today.dateByAddingTimeInterval(-24 * 60 * 60)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM