IOS: delete objects or reinitialize arrays in swift?

I am new to swift and I want to know if the beast is suitable for reusing an array to delete the entire object inside or reinitialize it.

For example, if I have:

var my_array:NSMutableArray! //global variable

      

and the first method I use:

func firstMethod{
    my_array = NSMutableArray()
    my_array.addObject("one")
    my_array.addObject("two")
    my_array.addObject("three")
    ...
}

      

for example, now in another method I need my_array to be empty:

the best solution is the following:

func newmethod() {
    my_array = NSMutableArray() //reinitialize (drastic method)
    //here, all new operation with my_array
}

      

or that?:

func newmethod() {
    if my_array == nil{
        my_array = NSMutableArray()
    } else {
        my_array.removeAllObjects()
    }
}

      

+3


source to share


2 answers


Why are you reinitializing the array, there is no need to reinitialize it. And if you reinitialize then it will point to a different memory address, so it would be better to reuse it without reinitializing. You can do it



if (my_array == nil){
            my_array = NSMutableArray();
        }
        else{
            //my_array.removeAllObjects();
            // Do your stuff here
        }

      

+1


source


The general answer is it depends. There is a serious danger when it comes to changing public properties, especially when it comes to multithreaded applications.

If you always reinitialize, it is more likely that you will be protected from multi-threaded problems.

If you deallocate the array, you are prone to multi-threading problems. You will likely run into indices outside of crashes and the like when you empty an array on one thread and try to access any index on another thread.

Thread A check the number of arrays. 10. Branch B empties the array. The array counter is now 0. Thread A tries to access the object at index 3. Crash.



Even though your code looks good, something like this:

if array.count > 3 {
    array[3].doThings()
}

      

Multithreading means that another thread mutates the array between this code checking the counter and this code accessing the index.

I would choose immutable objects as much as possible, and I would avoid mutating mutable objects that have any chance of being thread safe.

+2


source







All Articles