0

When the following code executes, it logs "0" even though the indexPath.row selected is "1".

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSInteger location = indexPath.row;
[userDefaults setInteger:location forKey:@"savedlocations"];
NSInteger location2 = [userDefaults integerForKey:@"savedlocation"];
NSLog(@"l: %ld", location);
somepers
  • 529
  • 2
  • 6
  • 9

2 Answers2

1

You've got several things that need to be fixed:

  • You're saving with the key savedlocations, but retrieving it with savedlocation. Note that the first is plural.
  • You're logging location, not location2, which is what's being pulled from NSUserDefaults. location2 will always be 0, because of the point above.
  • Edit: I had a third point here about calling synchronize, but it turns out that that is irrelevant to this situation, as explained by rmaddy in the comments below.

Other than those quick fixes, though, your configuration ought to work.

Nerrolken
  • 1,975
  • 3
  • 24
  • 53
  • 1
    Your last point is incorrect. You do not need to call `synchronize` to be able to read a value immediately. – rmaddy Aug 05 '15 at 21:17
  • @rmaddy The documentation says *"Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization"*. Can we assume that the automatic synchronization will always occur before we need to read the values? – Nerrolken Aug 05 '15 at 21:21
  • 1
    That's making a different point. The user defaults is nothing but a dictionary that is persisted to a plist file once in a while. When you set a value in user defaults, the in-memory dictionary is updated and can be read from immediately. It's the plist that gets updated on occasion. You can force the update of the plist with the call to `synchronize`. The only time you need to call `synchronize` is when the app goes to be background (to be safe) or after setting a really important value that must not be lost if the app crashes before the plist is updated on its own. – rmaddy Aug 05 '15 at 21:26
-1

You are looking for the key "savedlocation" instead of "savedlocations".

EDIT:

0 is being returned by the method, which is what is returned for an NSInteger that can't be found. My bad on the weird wording.

jrisberg
  • 764
  • 4
  • 16
  • There is no need to call `synchronize`. – rmaddy Aug 05 '15 at 21:27
  • And `integerForKey:` is not returning `null` for the wrong key. It's returning `0` since it is an `NSInteger`. – rmaddy Aug 05 '15 at 21:29
  • Took out the synchronize part, you're right on that. Sorry if my wording is confusing, I said it's returning 0, which is the "null" equivalent for an NSInteger in the eyes of the system – jrisberg Aug 05 '15 at 21:59