Object passed by reference will not exist. Swift

103 Views Asked by At

I have an array.

var array:[customType] = [] // pseudo code

func Generate_New_Array(){
    //initialization of generatedNewArray
    array = generatedNewArray
    for (index,element) in array{
         async_process({
         Update_Data_From_Web(&array[index])
         })
    }
    })
}

func Update_Data_From_Web(inout object:customType){
     download_process{
          object = downloadedData
     }
} 

The question is , what will should I do if I call Generate_New_Array before Update_Data_From_Web will finish for each of elements. They will store value back to not-existing index in array. How to avoid problems with that.

1

There are 1 best solutions below

2
On BEST ANSWER

You have a couple of options:

  1. Make the Generate_New_Array process cancelable, and then cancel the old one before starting the new one.

  2. Make the Generate_New_Array serial so that when you make a subsequent call to this method, it will finish the calls first. For example, you could have this enqueue an operation on a serial queue.

Regardless of which approach you adopt, if this is multithreaded code, make sure you synchronize your interaction with the model object (via GCD queues or locks or whatever).