iosswiftuisplitview

Showing fall back screen for UISplitview Secondary view when Object array is empty


I had a quick question related to initially loading the secondary view in UISplitView. I've currently got the code in my masterVC.swift to populate the detailsVC with the first object in an array if there is one. This works fine, the problem is that when the array is empty I predictably get fatal error: unexpectedly found nil while unwrapping an Optional value.

So my question is, when there are no objects, how can I set a separate "no objects founds" style screen to fall back on?

Thanks, here's the code from my MasterVC viewDidLoad

let initialIndexPath = NSIndexPath(forRow: 0, inSection: 0)
    if objects.count != 0 {
        self.tableView.selectRowAtIndexPath(initialIndexPath, animated: true, scrollPosition:UITableViewScrollPosition.None)

        if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
            self.performSegueWithIdentifier("showDetailsSegue", sender: initialIndexPath)
        }
    } else {
        // I'm guessing the code would go here.
    }

Solution

  • OK figured it out, here's what I needed to do.

    1. Create a new UIViewController, I just called it 'NoObjectVC' and connected it up.
    2. In storyboard hook it up to the SplitView Controller as a relationship segue Detail view controller, embed in navigation controller.
    3. Create a segue from the MasterVC, I called this 'noObjectSegue'
    4. In the prepareForSegue function of MasterVC add the following:

      else if segue.identifier == "noObjectSegue" {
       let navigationController = segue.destinationViewController as! UINavigationController
       let controller = navigationController.topViewController as! NoObjectVC
       controller.title = "No Objects Found"
      }
      
    5. Finally in the MasterVC, viewDidLoad() add:

      let initialIndexPath = NSIndexPath(forRow: 0, inSection: 0)
      
      if objects.count != 0 {
          self.tableView.selectRowAtIndexPath(initialIndexPath, animated: true, scrollPosition:UITableViewScrollPosition.None)
          if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
              self.performSegueWithIdentifier("showDetailSegue", sender: initialIndexPath)
          }
      } else {
          if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
              print("No Objects Available")
              self.performSegueWithIdentifier("noObjectSegue", sender: self)
          }
      }
      

    Not sure this will ever help anyone but I thought I'd document it just in case.