Siu Chung Chan
Siu Chung Chan

Reputation: 1686

how to avoid an object being deallocated?

static func appendMissingObjToArray(var oldArray:[AnyObject],newArray:[AnyObject]){
    for n in newArray{
        var isExist = false
        for o in oldArray{
            if(n.isEqual(o)){
                //exist
                isExist = true
                break
            }
        }
        if(!isExist){
            oldArray.append(n)
        }
    }
}

The above function is the append some data from newArray to oldArray. when this function is done. And getting data from the oldArray, I got BAD ACCESS error. so I think it is due to the newly added object in oldArray have been deallocated and the newArray is released.

Any thing I can do for avoid this?

Upvotes: 0

Views: 209

Answers (1)

simons
simons

Reputation: 2400

I believe that you need to declare your oldArray parameter as an inout. As follows:

//...
static func appendMissingObjToArray(inout oldArray:[AnyObject],newArray:[AnyObject]){
//...

You can then do e.g (note the ampersand & below:

class01.appendMissingObjToArray(&myOldArray, newArray: myNewArray)
println(myOldArray) // will contain the appended result

Done like this myOldArray (the passed array) will be mutated. So you may need to pass a copy of your original if retaining the original is important.

Upvotes: 1

Related Questions