2014-09-23 6 views
1

내 게임의 최고 기록을 저장하려고합니다. 나는 NSUserDefaults 통해 이것을하려고합니다. 이것은 내가 사용하고 코드입니다 :NSUserDefaults로 최고 기록 저장

//To save highest score 
var highestScore:Int = 20 
NSUserDefaults.standardUserDefaults().setObject(highestScore, forKey:"HighestScore") 
NSUserDefaults.standardUserDefaults().synchronize() 

//To get the saved score 
var savedScore: Int = NSUserDefaults.standardUserDefaults().objectForKey("HighestScore") as Int 
println(savedScore) 

하지만 "예상 선언"라는 NSUserDefaults에 오류가 나는 제대로이를 구현하는 방법을 알아낼 수 없습니다. 또는이 경우 NSArchiver을 사용해야합니까? 그렇다면 어떻게 구현할 수 있습니까?

+0

사이드 참고 : 쉽게 점수를 높일 기대하고 사용자가 변경할 수있는 PLIST에 NSUserDefaults 저장 데이터,. 개인적으로 몇 가지 앱에서 무제한 토큰을 성공적으로 제공했습니다. 이 데이터를 저장하는 더 나은 방법을 찾아보십시오. – erdekhayser

답변

3

NSCoding을 사용하십시오. 당신의 ViewController에 대한 그런 다음 스위프트 파일 "는 HighScore"

import Foundation 

class HighScore: NSObject { 

    var highScore: Int = 0 

    func encodeWithCoder(aCoder: NSCoder!) { 
      aCoder.encodeInteger(highScore, forKey: "highScore") 
    } 

    init(coder aDecoder: NSCoder!) { 
     highScore = aDecoder.decodeIntegerForKey("highScore") 
    } 

    override init() { 
    } 
} 

class SaveHighScore:NSObject { 

    var documentDirectories:NSArray = [] 
    var documentDirectory:String = "" 
    var path:String = "" 

    func ArchiveHighScore(#highScore: HighScore) { 
     documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 
     documentDirectory = documentDirectories.objectAtIndex(0) as String 
     path = documentDirectory.stringByAppendingPathComponent("highScore.archive") 

     if NSKeyedArchiver.archiveRootObject(highScore, toFile: path) { 
      println("Success writing to file!") 
     } else { 
      println("Unable to write to file!") 
     } 
    } 

    func RetrieveHighScore() -> NSObject { 
     var dataToRetrieve = HighScore() 
     documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 
     documentDirectory = documentDirectories.objectAtIndex(0) as String 
     path = documentDirectory.stringByAppendingPathComponent("highScore.archive") 
     if let dataToRetrieve2 = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? HighScore { 
      dataToRetrieve = dataToRetrieve2 
     } 
     return(dataToRetrieve) 
    } 
} 

만들기 :

import UIKit 


    class ViewController: UIViewController, UITextFieldDelegate { 
     var Score = HighScore() 

     override func viewDidLoad() { 
      super.viewDidLoad() 

     Score.highScore = 100 
     SaveHighScore().ArchiveHighScore(highScore: Score) 
     var retrievedHighScore = SaveHighScore().RetrieveHighScore() as HighScore 
     println(retrievedHighScore.highScore) 

     } 
    } 
+0

감사합니다. –

+0

안녕하세요. 코드를 구현했지만 RetrivedHighScore 기능을 사용하는 데 문제가 있습니다. 리턴 타입은 NSObject이므로 어떤 int 타입 변수와도 비교할 수 없습니다. Ints와 비교하기 위해 데이터를 어떻게 관리합니까? 예를 들어, 현재 점수가 dataToRetrive 변수의 저장된 점수보다 높은지 알고 싶습니다. –

+0

다음과 같이 highScore에 액세스해야합니다. retrievedHighScore.highScore. 내가 한 방식. RetrieveHighScore 함수에 대한 호출은 NSObject이지만,에 의해 HighScore 정수에 액세스 할 수 있습니다. 명명법. Object 호출없이 정수를 저장하는 코드를 다시 작성할 수 있지만 현재의 더 복잡한 방법은 다른 것을 추가 할 수있는 함수를 제공합니다. 나중에 하나 이상의 변수를 저장하고자하는 프로젝트와 정수가 아닌 다른 유형의 프로젝트를 NSObject에 묻을 수 있습니다. –