2014-12-26 2 views
-1

난이도 정수를 저장하고로드하는 데 문제가 있습니다.정수 저장 오류 및로드 신속한

let SecondDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() 
     var difficulty = SecondDefaults.valueForKey("Difficulty")?.integerValue 
     SecondDefaults.synchronize() 
     Difficulty = difficulty!.stringByTrimmingCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).toInt()! 
+1

입니까? 그것은 빠른 정수입니까? – Cezar

+0

그것은 단지 정수입니다. – SRL

+0

어떻게/어디서 난이도를 설정합니까? 그리고 int 인 경우 왜 문자열로 검색합니까? –

답변

0

당신은 변경해야 로딩을 위해있는 viewDidLoad에서 다른보기에

(이 하나의 어려움은)

Difficulty + 1 

    let SecondDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() 
    SecondDefaults.setObject(Difficulty, forKey: "Difficulty") 
    SecondDefaults.synchronize() 

: 나는 버튼이 하나 개의보기에 그것을 결정 밀려 있습니다 :

var difficulty = SecondDefaults.valueForKey("Difficulty") as? String 

,691에
var difficulty = SecondDefaults.valueForKey("Difficulty")?.stringValue 

왜 정수를 문자열로 변환해야하는지 모르겠습니다. NSUserDefaults에서 문자열을 문자열로 변환 할 필요가없는 정수를 가져 오는 데 필요한 코드는 다음과 같습니다.

let SecondDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() 
var difficulty = SecondDefaults.valueForKey("Difficulty")?.integerValue 
0

귀하의 문제는이 라인에있다 :

var difficulty = SecondDefaults.valueForKey("Difficulty") as? String

문제는 값이 String이 될 수도 있고 무기 호 수 있다는 것이다. 누가 알아? as? 키워드는 캐스트가 실패 할 수 있음을 나타내 므로 어려움은 선택적이며 사용자가 암시 적으로 랩핑하지 않습니다. nil로 언랩하면 런타임 오류가 발생합니다.

두 번째 코드 조각에서 Difficulty 유형 Int의 것을 가정 할 때,이 작동합니다 : 난이도가 개체의 어떤 종류의

let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() 
let maybeDifficulty = defaults.valueForKey("Difficulty") as? Int 
if let difficulty = maybeDifficulty { 
    Difficulty = difficulty 
} else { 
    println("Difficulty is not an Int or may be nil") 
}