Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

xcode - iOS App Crashes on Phone but works fine on simulator

I have the following code:

var displayValue: Double{
    get{
        println("display.text =(display.text!)")
        return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
    }
    set{
        display.text = "(newValue)"
        userIsInTheMiddleOfTypingANumber = false;
    }
}

It works fine in the simulator. but when I try it on phone it crashes. here is the console:

digit= 3
display.text =3
operandStack =[3.0]
digit= 2
display.text =2
operandStack =[3.0, 2.0]
display.text =6.0
fatal error: unexpectedly found nil while unwrapping an Optional value

This line:

NSNumberFormatter().numberFromString(display.text!)!

is returning nil which causing the app to crash cause it couldn't unwrap the optional. I really don't know what's wrong. I'm following some tutorials in iTunes U.

any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try:

get{
    println("display.text =(display.text!)")
    let formatter = NSNumberFormatter()
    formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    return formatter.numberFromString(display.text!)!.doubleValue
}

Because, NSNumberFormatter uses devices locale by default, it's possible that the decimal separator is not ".". For example:

let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "ar-SA")
print(formatter.decimalSeparator!) // -> outputs "?"
formatter.numberFromString("6.0") // -> nil

The formatter that uses such locales cannot parse strings like "6.0". So if you want consistent result from the formatter, you should explicitly specify the locale.

As for en_US_POSIX locale, see the document:

In most cases the best locale to choose is en_US_POSIX, a locale that's specifically designed to yield US English results regardless of both user and system preferences. en_US_POSIX is also invariant in time (if the US, at some point in the future, changes the way it formats dates, en_US will change to reflect the new behavior, but en_US_POSIX will not), and between platforms (en_US_POSIX works the same on iPhone OS as it does on OS X, and as it does on other platforms).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...