Emptyless Emptyless - 5 months ago 22
iOS Question

Segue value nil in ViewDidLoad but has value in didSet

I am passing a Core Data entity to the next View Controller with a

prepareForSegue
like this:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "MemberDetails" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("MemberDetails") as! MemberDetails
let index = self.memberTable.indexPathForSelectedRow
if searchPredicate == nil {
let member = self.sections[index!.section].members[index!.row]
member.printMember()
vc.member = member
} else {
vc.member = self.filteredMembers[index!.row]
}

}
}


And in my receiving View Controller i have this:

var member : Member? {
didSet {
print("")
print(" --------------------- ")
print("")
member?.printMember()
}
}

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.

print("")
print(" --------View Did Load -------- ")
print("")
self.member?.printMember()
}


With the following output:


----------_-----------

// member.printMember() function output

--------View Did Load --------

// no ouput -> object is nil


This means that the didSet happens before the viewDidLoad and it has values but for some reason it is emptied again when the viewDidLoad is executed (object = nil)

Why is this happening? / How do i mitigate this effect?

Answer

I think you misunderstood what a segue is.

You are instantiating a new MemberDetails on prepareForSegue

 let storyboard = UIStoryboard(name: "Main", bundle: nil)
 let vc = storyboard.instantiateViewControllerWithIdentifier("MemberDetails") as! MemberDetails

If the prepareForSegue method is called, this means a viewController from the storyboard is already being loaded

what you need is

if segue.identifier == "MemberDetails" {
      if let vc = segue.destinationViewController as? MemberDetails{
           let index = self.memberTable.indexPathForSelectedRow
           if searchPredicate == nil {
                let member = self.sections[index!.section].members[index!.row]
                member.printMember()
                vc.member = member
           } else {
                vc.member = self.filteredMembers[index!.row]
           }
       }
}