1

I'm trying to save time taken to complete each level. so im looking for a better way to save data, i have 100 variables for all levels i.e, leveltime1, levetime2....and so on..leveltime100 I have this code which is not working

var leveltime : [Int] = [leveltime1, levetime2, leveltime3......leveltime100]
defaults.setInteger("leveltime[Currentlevel -1]")
leveltime[Currentlevel -1] = defaults.integerForKey("leveltime[Currentlevel -1]")

so this is not working. is there any other way ? other than if else and switch statement?

user528432
  • 411
  • 2
  • 5
  • 18

1 Answers1

1

lets assume you are in level 3 and want to save the time you needed

var level = 3
var time = 21

now you want to safe this to your defaults, for this you generate a key (string)

var key = "leveltime-\(level)"

and store the time

var defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(time,key)

done.

to retrieve this at some point in time

var level = 3
var key = "leveltime-\(level)"
var defaults = NSUserDefaults.standardUserDefaults()
var time = defaults.integerForKey(key)
Sebastian Flückiger
  • 5,525
  • 8
  • 33
  • 69
  • runs just fine here. the upper one will likely not work as you expect as it does not convert the level number in the string, try the second block :) – Sebastian Flückiger Dec 31 '14 at 10:35
  • check this out http://i.imgur.com/WhZowaQ.png and console http://i.imgur.com/ur33c3P.png when i started the app , all 4 levels were 0 , as u can see i completed 4 levels in 7,9.. seconds and then went back to main menu and value was still 0 0 0 0 – user528432 Dec 31 '14 at 10:48
  • may b its saving for "levelkey" but timelevel1...2.3 – user528432 Dec 31 '14 at 10:53
  • you changed my answer :) you are saving all results to "levelkey". there is no need for the `"` there. look at my code again. `forKey: levelkey` not `forKey: "levelkey"` :) levelkey is already a string, you do not need to put it in "". – Sebastian Flückiger Dec 31 '14 at 11:03
  • still no luck, looks like ill have to go with switch or if else statement which will take over 300 lines – user528432 Dec 31 '14 at 11:20
  • no you dont! this solutions works 100%, you must have made a error somewhere :) please update your post with the new code you have running now. – Sebastian Flückiger Dec 31 '14 at 11:24
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/67979/discussion-between-sebastian-fluckiger-and-djay). – Sebastian Flückiger Dec 31 '14 at 11:25