user3746428
user3746428

Reputation: 11175

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.

Upvotes: 0

Views: 1358

Answers (3)

gnasher729
gnasher729

Reputation: 52538

Make sure you don't paint yourself in a corner. An NSIndexPath contains two numbers, not one: A section and a row within that section. In trivial cases when a table view has only one section the section number will always be zero, but you will get more complicated cases.

If you want to store index paths, I would add a category to NSUserDefaults with one method that turns an NSIndexPath into a dictionary with keys section and row and writes that, and one that reads a dictionary and creates an NSIndexPath with the values for section and row.

That said, a row number is something horribly unstable. Your UI designers decide that two rows have to change their order, and all your preferences are broken. What I do is one enum that identifies the purpose of each row; that enum must never, ever, ever change its values, and that is stored in the preference. And then there is another enum that refers to items in the UI, and that can change freely.

Upvotes: 1

Rahul Mayani
Rahul Mayani

Reputation: 3831

Saving A Row(integer) Value :

NSUserDefaults.standardUserDefaults().setInteger(indexPath.row, forKey: "row")
NSUserDefaults.standardUserDefaults().synchronize()

Loading A Row(integer) Value:

 row() -> Int
 var row = NSUserDefaults.standardUserDefaults().integerForKey("row")

Upvotes: 0

lchamp
lchamp

Reputation: 6612

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) ;

Upvotes: 2

Related Questions