Search code examples
iosobjective-canimationautomatic-ref-countingbridge

beginAnimations with "context"variable in ARC?


The question partially similar to existing ones but I still get error with memory management.

The following non-ARC code work:

[UIView beginAnimations:... context:[[NSNumber numberWithInt:i] retain]];

and somewhere in didStopSelector:

NSNumber * n = (NSNumber *)context;
...
[n release];

I tried to remove retain/release and to add copy (and combined these ways) but with no effect.

Additionally I saw another similar question:

UIView Animation on multiple UIImageViews in ARC

They pass imageName variable as context but they don't describe if it is retained or autoreleased.

Questions:

1)How to convert my code to ARC correctly?

2)Is there any difference in code if you pass retained/autoreleased context (of cousre, if autoreleased will work in general)?


Solution

  • Try __bridge_retained to retain object and cast it to void*

    void *context = (__bridge_retained void *)( @1000 );
    

    and then in animationDidStop you have to transfer ownership with __bridge_transfer. At this point ARC should naturally release the object in current autorelease pool.

    - (void)animationDidStop:(void *)context {
       NSNumber *n = (__bridge_transfer id)context;
    }
    

    Alternatively you can switch to block based API and reference views directly.