Ben Sullivan
Ben Sullivan

Reputation: 2154

ViewDidLoad calling again after segue performed

I am experiencing an unusual error when segueing back to my main view controller.

When a user registers within the app it creates a unique CloudKit record. Once the save operation is completed, an NSNotification is broadcast from the cloudKit saveRecord closure which displays an alert to the user. When the alert is accepted a segue to a new viewController is performed.

When segueing back to the main view controller it runs viewDidLoad & viewDidAppear again, causing various functions to stop working. I have found that the original instance of my main view controller is still in memory and can be accessed.

I believe the issue could have something to do with threading and the performForSegue being called off of the main thread, although I'm using GCD and this shouldn't be the case.

Here is my code:

Save function:

func saveRecord(newUser: CKRecord) {

database.saveRecord(newUser) { record, error in

  if error != nil {

    print(error)
    Properties.registrationError = error

  } else {

    Properties.registrationSuccess = record
    print(record)
  }

    NSNotificationCenter.defaultCenter().postNotificationName(Key.Registration, object: self)
 }
}

When the saveRecord notification is received:

func registrationComplete() {
 dispatch_async(dispatch_get_main_queue()) {

  self.pleaseWait.alpha = 0
  self.stopIndicator()
  print("stop indicator")

  if Properties.registrationError != nil {

    self.displayAlert("Registration Failed", error: "\(Properties.registrationError!.localizedDescription)", performAction: .None)

  } else {

    self.displayAlert("Registration Completed", error: "Press OK to begin induction", performAction: .BeginInduction)
  }
 }
}

When OK is pressed:

self.performSegueWithIdentifier("beginInduction", sender: self)

For testing I am segueing straight back to the main controller when the new view appears. At this point the original controller's viewDidLoad is run again. Any help would be appreciated, thank you!

Upvotes: 0

Views: 697

Answers (1)

Pradeep K
Pradeep K

Reputation: 3661

When you call performSegueWithIdentifier it will load a new view controller associated with "beginInduction" identifier and not go back to the existing instance which you may have created with a pervious performSegueWithIdentifier. What you have to do is to use an unwind segue.

More details are in this link.

https://developer.apple.com/library/ios/technotes/tn2298/_index.html

Alternatively you can use popToRootViewControllerAnimated or popToViewController or popViewController or dismissViewController methods to go back to the pervious view controllers

Upvotes: 2

Related Questions