memory management - Purposely Create Retain Cycle (Objective C without GC) -


is there ever case purposely creating retain cycle prevent deallocation, cleaning later, best solution problem?

if so, there examples of in cocoa touch or nextstep frameworks?

i intend question specific objective c arc since objective c gc or other languages gc may behave differently.

sure. it's not uncommon, though may not realize it.

for example, let's assume controller making network request, , really need make sure handle response, if user has navigated away controller.

i might this:

- (void)donetworkthing {     __block mycontroller *blockself = self;      nsurlrequest *request = // request     [nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue mainqueue] completionhandler:       ^(nsurlresponse *response, nsdata *data, nserror *error) {           // handle response here           [blockself dothingwithresponse:response];       }]; } 

this introduces trivial retain cycle self has caused retained assigning strong pointer blockself. until blockself goes out of scope, self not deallocated.

note often, use weak pointer in situation. if need controller around handle it, using strong pointer works too. handler block deallocated, reference blockself go away. since the stack reference blockself gone self deallocated if nobody else holding on it.

so basically, blockself caused temporary retain cycle, useful in ensuring deallocation not happen until request finished. because arc automatically cleans retain counts when __block variable goes out of scope, doesn't retain cycle. nevertheless, that's is.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -