Need to free memory after Modal Segues, but I need both my Segues to pass data from A to B and B to A - swift

I am making a game for iOS with SpriteKit.
I have 2 Viewcontrollers. One is the GameViewController and the other one is the MenuViewController. Let's call them A and B respectively.
When the player dies, a function is called in GameScene.swift that launches a modal "Lost" Segue to B. There, the player can restart the game or buy a life and a "Back" Segue is called to A.
I need to dismiss the additional Views that get created each time I call a segue.
Problem is: I need the "Lost" Segue to send data about the Score to View B and I need the "Back" Segue to send data to View A about wether or not the player used a life.
I have implemented all this. But now I need to find how to dismiss old views that keep eating the device's memory, thus leading to lag and crash.
I have googled for hours and hours. No solution was adapted to my situation.
The solutions I found either caused my app to bug, data not to be passed or views not to be generated.
I will not add code here since there is a LOT. But I am sure the answer is actually really easy, just not for a beginner like me.
I think a possible solution would be an unwind segue from B to A ?
But do unwind segues pass data along ?
Moreover, I found no answer I could understand on how to use an unwind segue.
I exhausted all my possibilities. Stack Exchange is my last chance.

You definitely should use an unwind segue to return to the previous viewController, otherwise as you have found your memory usage increases until your apps quits.
I created the following example from your description. It uses a standard segue to move from the GameViewController to the MenuViewController and it uses an unwind segue to move from the MenuViewController back to the GameViewController.
The GameViewController has a Player Dies UIButton, a UITextField for entering a score, and a UILabel for displaying the lives.
The MenuViewController has a UILabel for showing the score, a Buy a Life UIButton for adding lives, and a Restart UIButton for returning to the GameViewController.
Here's the code:
GameViewController.swift
import UIKit
class GameViewController: UIViewController {
#IBOutlet weak var scoreTextField: UITextField!
#IBOutlet weak var livesLabel: UILabel!
var lives = 3
func updateLivesLabel() {
livesLabel.text = "Lives: \(lives)"
}
override func viewDidLoad() {
super.viewDidLoad()
updateLivesLabel()
}
// This is the function that the unwind segue returns to.
// You can call it anything you want, but it has to be in
// the viewController you are returning to, it must be tagged
// with #IBAction and it must take a UIStoryboardSegue as its
// only parameter.
#IBAction func returnFromMenu(segue: UIStoryboardSegue) {
print("We're back in GameViewController")
// Update the lives label based upon the value passed in
// prepareForSegue from the MenuViewController.
updateLivesLabel()
}
#IBAction func goPlayerDies(sender: UIButton) {
lives--
self.performSegueWithIdentifier("Lost", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Lost" {
let destinationVC = segue.destinationViewController as! MenuViewController
destinationVC.score = Int(scoreTextField.text ?? "") ?? 0
destinationVC.lives = lives
}
}
}
MenuViewController.swift
import UIKit
class MenuViewController: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
var score = 0
var lives = 0
override func viewDidLoad() {
super.viewDidLoad()
scoreLabel.text = "Score: \(score)"
}
#IBAction func buyLife(sender: UIButton) {
lives++
}
#IBAction func goRestart(sender: UIButton) {
self.performSegueWithIdentifier("Back", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Back" {
let destinationVC = segue.destinationViewController as! GameViewController
destinationVC.lives = lives
}
}
}
This is how you wire up the forward segue to be called programmatically:
Control-drag from ViewController icon to the MenuViewController:
Select Present Modally from the pop-up:
Click on the segue arrow between the viewControllers and give it an identifier in the Attributes Inspector:
This is how you wire up the unwind segue to be called programmatically:
Control-drag from ViewController icon to Exit icon:
Choose returnFromMenu from pop-up:
Click on the Unwind Segue in the Document Outline and give it the identifier "Back" in the Attributes Inspector on the right:
Alternate Answer
Instead of using segues, you can present and dismiss viewControllers manually. The advantage for your app is that the MenuViewController will be allocated only once and will persist for the life of the app. This same viewController will be presented and dismissed repeatedly, but it will not be deallocated which I suspect is leading to your crashes.
The GameViewController will be the initialViewController that is created by the Storyboard. The MenuViewController will be loaded in viewDidLoad of the GameViewController.
To make this work, you need to add an identifier to the MenuViewController so that it can be instantiated by name. Click on the MenuViewController in the Storyboard and set its Storyboard ID in the Identity Inspector:
Here is the code. Note that all mention of segues is gone. Note how viewWillAppear is used to update the viewControllers.
GameViewController.swift
import UIKit
class GameViewController: UIViewController {
#IBOutlet weak var scoreTextField: UITextField!
#IBOutlet weak var livesLabel: UILabel!
var menuViewController: MenuViewController?
var lives = 3
func updateLivesLabel() {
livesLabel.text = "Lives: \(lives)"
}
override func viewDidLoad() {
super.viewDidLoad()
menuViewController = self.storyboard!.instantiateViewControllerWithIdentifier("MenuViewController") as? MenuViewController
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateLivesLabel()
}
#IBAction func goPlayerDies(sender: UIButton) {
lives--
menuViewController?.score = Int(scoreTextField.text ?? "") ?? 0
menuViewController?.lives = lives
self.presentViewController(menuViewController!, animated: true, completion: nil)
}
}
MenuViewController.swift
import UIKit
class MenuViewController: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
var score = 0
var lives = 0
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
scoreLabel.text = "Score: \(score)"
}
#IBAction func buyLife(sender: UIButton) {
lives++
}
#IBAction func goRestart(sender: UIButton) {
let destinationVC = self.presentingViewController as! GameViewController
destinationVC.lives = lives
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}

Related

Retrieving a variable from another view controller

The variable latitude in ViewController1 is visible. Why is the variable from another ViewController empty? Whenever I run the code the .text property of ActualCoordinatesText label is empty...
class ViewControllerGpsMaps: UIViewController {
#IBOutlet weak var ActualCoordinatesText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func GetCoordinates(_ sender: Any) {
GetActualCoordinates()
}
public func GetActualCoordinates() {
let sb = storyboard?.instantiateViewController(withIdentifier: "ViewController1") as! ViewController
ActualCoordinatesText.text = sb.latitude
}
}
Thanks for the help!
You are recreating a new instance of ViewController1 that means that the data included is the initialized value...
If your ViewControllerGPSMaps is called by VieController1 you should use the prepare(for segue:, sender:) of the ViewController1 to "give" the data you want to transfer...

Use closure to pass data between two controllers

my problem looks so simple, but since I am a beginner, I have problem to understand the concept of the closure to pass data between two controllers
for example I have a static table view controllers that has one cell and a title inside it
class FirstView: UITableViewController {
#IBOutlet weak var titleLabel: UILabel!
and I have an another view controller that contain a button inside it
class SecondViewController: UIViewController {
#IBAction func pressChangeButton(_ sender: UIButton) {
}
and there is segue1 between these two controllers, with identifier "segue1"
I want a to a simple task, I want to add a boolean closure that it will be true if the change button is pressed.
that is why I create a closure function the second view controller that has change button.
var change : ((Bool) -> Void)?
I just want, that the second view controllers tells the first one that change closure is now true (after pressing the change button) and the first view controllers simply change the title table inside it to whatever (I just want to see that how it can be done)
I don't know I have to use prepare sugue function?
Could anyone help me to understand this concept?
You can try
class FirstView: UITableViewController {
#IBOutlet weak var titleLabel: UILabel!
#IBAction func goToSecond(_ sender: UIButton) {
self.performSegue(withIdentifier: "segue1", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue1" {
let des = segue.destination as! SecondViewController
des.change = { [weak self] (value) in
print(value)
self?.titleLabel.text = "SetValue"// set a value
}
}
}
}
class SecondViewController: UIViewController {
var change : ((Bool) -> Void)?
#IBAction func pressChangeButton(_ sender: UIButton) {
change?(true)
}
}
A closure is basically a piece of code that you can run. In Swift a closure is a first class citizen as it can be passed around as parameters and return type of functions. That being said, you can pass or set a closure as you normally would for other objects.
As per Sh_Kan's answer, just set SecondViewController's closure in prepare(for segue:sender:), always paying extra attention to retain cycles. You might also want to take a look at delegate design pattern in order to exchange data and messages between your controllers.

Delegate using Container View in Swift

I'm developing an app for iPad Pro. In this app, containerView use to add additional views and interact with them.
First, I created a protocol:
protocol DataViewDelegate {
func setTouch(touch: Bool)
}
Then, I created my first view controller
import UIKit
class ViewController: UIViewController, DataViewDelegate {
#IBOutlet var container: UIView!
#IBOutlet var labelText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
func setTouch(touch: Bool) {
if touch == true {
labelText.text = "Touch!"
}
}
}
And finally, I created a view that will be embedded in containerView.
import UIKit
class ContainerViewController: UIViewController {
var dataViewDelegate: DataViewDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func touchMe(sender: AnyObject) {
dataViewDelegate?. setTouch(true)
}
}
But for some reason, nothing happened, the first view controller receives nothing in setTouch function.
My question is: In this case, using container, how can I make the communication between two ViewsControllers?
Like #nwales said you haven't yet set the delegate. You should do set the delegate in prepareForSegue function on your first viewController (who contain the viewContainer)
First select the embed segue and set an identifier in the attributes inspector.
Then in the parentViewController implement the func prepareForSegue like this:
Swift 4+:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "the identifier") {
let embedVC = segue.destination as! ViewController
embedVC.delegate = self
}
}
Below:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if (segue.identifier == "the identifier") {
let embedVC = segue.destinationViewController as! ContainerViewController
embedVC.dataViewDelegate = self
}
}
Looks like you defined the delegate, but have not set the delegate. This happens to me all the time.

How to send my score variable to another view controller?

After I click on a button I go to a new view controller.
I made it possible to make points with var score = 0 in a IBOutlet and to show to points I use Score.text = "\(++score)".
How can I pass the score to the 'Game over' screen/view controller to a label called "resultScore"?
Add an attribute secondViewController in the destination view controller, and use prepareForSegue
Current View Controller
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "segueTest") {
var svc = segue!.destinationViewController as secondViewController;
svc.toPass = textField.text
}
}
in secondViewController you can define one variable like String
var toPass:String!
In the secondViewController under the viewDidLoad function add this code
println(\(toPass))
One easy way to achieve that is you can use NSUserDefault for that.
first of all in your playScene when you are increasing your score you can store your score this way:
Score.text = "\(++score)"
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "userScore")
After that in your next view controller you can get score this way:
resultScore = NSUserDefaults.standardUserDefaults().integerForKey("userScore")
Remember that type of your resultScore should be Int.
FirstViewController
#IBOutlet weak var textField: UITextField!
...
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let vc = segue.destinationViewController as? GameOverViewController {
vc.score = Int(textField?.text)
}
}
...
SecondViewController
var score: Int!
#IBOutlet weak var label: UILabel!
...
override func viewDidLoad() {
super.viewDidLoad()
label.text = String(score)
}
This method will call when button was pressed, and in this place you may set some properties for your second view controller

Increase a counter in the first interface controller by pressing a button in the second interface controller

I would like to increase the value of the property in the first interface controller in the IBAction (Add1) method of the second interface controller
and then use the value of this property to update the label when the first view controller is activated
I was able to increase the value , but the value increases even if I press the back button.
I need to find a solution so that when I press the IBAction in the second interface controller , I can get that result and use it in the first interface controller and update the label.
here is the code:
First interface controller:
Blockquote
#IBOutlet weak var resultButtonLabel: WKInterfaceButton!
#IBAction func resultButton() {
pushControllerWithName("secondInterfaceController", context: self)
}
override func willActivate() {
super.willActivate()
resultButtonLabel.setTitle("\(counter++)")
}
Blockquote
Second interface controller:
Blockquote
var counter = 1
#IBAction func weScored() {
counter++
popController()
}
Blockquote
The easy way to implement this idea is use of NSUserDefaults
In your firstViewController you can read values form NSUserDefaults this way:
override func viewDidLoad() {
super.viewDidLoad()
let score = NSUserDefaults().integerForKey("Score")
resultButtonLabel.text = "\(score)"
}
and into your SecondViewController you can increase this counter with NSUserDefaults this way:
import UIKit
class SecondViewController: UIViewController {
var counter = Int()
override func viewDidLoad() {
super.viewDidLoad()
counter = NSUserDefaults().integerForKey("Score")
}
#IBAction func weScored(sender: AnyObject) {
counter++
NSUserDefaults().setInteger(counter, forKey: "Score")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}
}
Hope this will help.