Do we release an argument in fast enumeration

112 views Asked by At

do we release an argument in fast enumeration? Therefore would this code be accurate:

    for (MKCircle *circle in localOverlays) {

    [mapView addOverlay: circle];

    [circle release]; // Is it perfectly alright to call this?
}

I am just wondering, my first time working with fast enumeration!

3

There are 3 answers

1
JeremyP On BEST ANSWER

The answer is in the Apple Memory Management Rules.

  • You own any object you create

    You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy”

Did you create circle? No.

You can take ownership of an object using retain

Did you retain circle? No.

So you don't own the object.

You must not relinquish ownership of an object you do not own

That seems fairly straight forward now that you have determined you don't own circle. The release in the example code in your question should not be there. In fact, most likely, it will cause a crash somewhere down the line.

0
Sergey Kalinichenko On

Fast enumeration does not usually create new objects, it is going through the existing ones. That is why it is almost never the right thing to do: fast enumeration of regular containers (NSArray, NSSet, NSDictionary) does not retain objects before making them available to the loop, so releasing them would be an error. Even inside a dealloc method you shouldn't do it: releasing the container releases its items too, so you shouldn't be releasing them individually.

0
fengd On

No. I don't think it's the right thing to do. It neither do a retain nor a release to the instance

for (MKCircle *circle in localOverlays) {

    [mapView addOverlay: circle]; //retain here
}

addOverley: should do a retain to circle, and it's mapView's responsibility to release when mapView doesn't needs it

Simple guide, you retain it, and release it when you done using it