Search code examples
iosswiftnsuserdefaults

accessing NSUserDefaults within cellForRow(at:IndexPath) in Swift, memory usage


Is it memory intensive to retrieve data from NSUserDefaults within the cellForRow(at:IndexPath method? Code shown below:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let recentFavorite = UserDefaults.standard.string("recentlyStoredFavorite")
  if self.favorite == recentFavorite {
    cell.imgForFavorite = self.imgForFavorite
  }
}

Or should I save the value from UserDefaults in viewWillAppear and use that within cellForRow?

Please help me understand the memory implications of both the choices.


Solution

  • According to Apple

    At runtime, you use UserDefaults objects to read the defaults that your app uses from a user’s defaults database. UserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value.

    You should be 'ok' to retrieve the info in cellForRow, as its likely sitting in a dictionary in memory (assumption), fetched by the key you provide, however to vadian's point, you could just put it in a model or property and eliminate the assumption.

    Also, consider if that data will be changed by another process and if you need to observe UserDefaults key.