Search code examples
iosswiftseguensindexpathnsinteger

Converting NSIndexPath to NSInteger in Swift


I have a UITableView with a segue that connects to a view controller. When the user taps on a cell, I would like the indexPath.row to be passed to that view controller so I can update the content in the view based on which cell has been tapped.

I am aware of the different methods of doing this, however I would like to use NSUserDefaults() for my particular use. The problem is that I don't know how to convert the indexPath.row into an integer to be saved into NSUserDefaults(). This is what I have tried:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    println(indexPath.row)
    NSUserDefaults.standardUserDefaults().setObject(NSInteger(indexPath.row), forKey: "index")

    self.performSegueWithIdentifier("event", sender: self)
}

Second View Controller:

override func viewDidAppear(animated: Bool) {
    println(NSUserDefaults.standardUserDefaults().integerForKey("event"))
}

At the moment, when I try to print out the indexPath.row in the next view controller, it always just returns 0.


Solution

  • You aren't using the same key

    NSUserDefaults.standardUserDefaults().setObject(NSInteger(indexPath.row), forKey: "index") // <--- INDEX
    
    NSUserDefaults.standardUserDefaults().integerForKey("event")) // <-- EVENT
    

    Also you :

    • Might want to save it / read it with the equivalent method setInteger:forKey: and integerForKey:
    • Don't have to convert the value (it's already an integer) ;