sunshinejr / SwiftyUserDefaults

Modern Swift API for NSUserDefaults
http://radex.io/swift/nsuserdefaults/static
MIT License
4.85k stars 365 forks source link

Error: Simultaneous accesses error #241

Closed kaunteya-suryawanshi closed 3 years ago

kaunteya-suryawanshi commented 4 years ago

I am using this library to store the font size of cells that are added to the TableView

Whenever the user increases the fontSize, I increment the value which eventually triggers the observer. Here is the code

// This function increments the fontSize
@IBAction func increaseFontSize(_ sender: NSMenuItem) {
    Defaults.fontSize += 1
}

// This is the observer that is defined in the `viewDidLoad` of ViewController
fontSizeObserver = Defaults.observe(\.fontSize) { [weak self] update in
   guard update.newValue != update.oldValue else { return }
   self?.tableView.reloadData()
}

Since I am reloading the tableView, it is invoking the heightForRow method which is required to determine the height of the cell

Now since height of the cells is proportional to the font size, I am doing this

func tableView(height forRow for item) {
   return CGFloat(Defaults.fontSize) * 1.2 <------ Memoery access error
}

Here on above line I am getting following error

Thread 1: Simultaneous accesses to 0x10075d2f0, but modification requires exclusive access

mman commented 4 years ago

Yeah this, is an interesting one. Temporary fix is for you to use update.newValue via temporary variable to do the new calculation. But a better and more systematic fix would be needed in the library.

moyoteg commented 3 years ago

@kaunteya-suryawanshi were you able to solve this?

kaunteya commented 3 years ago

@moyoteg You can use the newValue which is received in the closure parameter instead of Defaults.xyz if possible. I was not able to use the value from closure parameter because the call to tableView(height:forRow) is implicit when tableView.reloadData() is invoked.

Or you can even try

DispatchQueue.main.async {
      // Your code that access Defaults.xyz
}

I have moved away from SwiftyUserDefauts, hence its difficult to recollect what solution I had use back then

sunshinejr commented 3 years ago

Hey all. I just released 5.2.0 with the fix for that. Let me know if this helps - thanks!