1

I ran into an interesting problem today while trying to abstract some business logic from my view controller into a view controller model. The process now goes like this:

View Controller Interaction -> 
    Trigger struct's mutating function -> 
        Call back to view controller when done -> 
            Access the struct's list property to perform a count

As this was the first time I've encountered this issue, I did a little digging around why this is the case. The problem appears to arise as the mutating method has exclusive access to the memory location for the duration of its function, only releasing when the function returns (along with providing a new memory address). Meaning that technically speaking, my function hasn't necessarily ceased it's execution before my view controller attempts to access it, resulting in a crash:

Simultaneous accesses to <Address>, but modification requires exclusive access

So this is the basic structure of what I'm doing. Maybe someone has a better solution architecturally.

class A : UIViewController {
    var listStructure = B()

    func tellStructToDoSomethingToList() {
        listStructure.doSomethingToList() { completion in
            if completion {
                print(listStructure.list.count)
            }
        }
    }
}

Then:

struct B {
    var list: String = []

    mutating func doSomethingToList(completion: (_ didUpdateList: Bool) -> ()) {
        // do some stuff to the list
        completion(true)
    }
}

How might one structure this to avoid simultaneous memory access violations? I tried this using a protocol/delegate pattern as well - but had the same problem.

This issue is also discussed:

Karim
  • 271
  • 2
  • 11

0 Answers0