Reputation: 3
I'm building a simple tic tac toe game and I would like to same each "X" or "O" in an array so that when the user leaves the screen and comes back the game reloads.
I can get it to print to the output screen but it doesn't show up in the IOS simulator. I've only have the first two squares coded because I was hoping to get the array to work before I moved on to the rest.
Here's my code:
import UIKit
var gamePieces3 = NSMutableArray()
class GameViewController3 : UIViewController {
@IBOutlet var button0 : UIButton !
@IBOutlet var button1 : UIButton !
@IBOutlet var spot0 : UIImageView !
@IBOutlet var spot1 : UIImageView !
@IBAction func addGamePiece0(button0 : AnyObject) {
if (goNumber % 2 == 0) {
let image2 = UIImage(named : "cross.png")
spot0.image = image2
}
else {
let image1 = UIImage(named : "circle.png")
spot0.image = image1
}
gamePieces3.addObject(spot0)
goNumber++
}
@IBAction func addGamePiece1(button1 : AnyObject) {
if (goNumber % 2 == 0) {
let image2 = UIImage(named : "cross.png")
spot1.image = image2
}
else {
let image1 = UIImage(named : "circle.png")
spot1.image = image1
}
gamePieces3.addObject(spot1)
goNumber++
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidAppear(animated : Bool) {
print(gamePieces3)
}
}
Upvotes: 0
Views: 146
Reputation: 1108
There are more things you need to implement in your code if you want your app to "remember" where it left off from last app close or exit. Since you only want to store which button location stores "cross" or "circle", I think most suitable and easy way to do is using NSUserDefaults
. It works very similar to a Dictionary. You can put something like "Button0" all the way to "Button8" as keys, and "cross.png" or "circle.png" as value. Every time your gamePieces3
is changed, you need to change that NSUserDefaults
accordingly. Then in you videDidLoad
, you want to read from your NSUserDefaults
. Scan through NSUserDefaults
, and apply "cross.png" or "circle.png" accordingly to controller's view.
Upvotes: 1