Re: autorelease: how does this work!? (if at all)
Re: autorelease: how does this work!? (if at all)
- Subject: Re: autorelease: how does this work!? (if at all)
- From: Julien Jalon <email@hidden>
- Date: Fri, 18 Jun 2010 17:36:35 +0200
"Is the compiler/runtime being clever enough to retain it because it is
going to be needed in the inner block (if so: very clever!)?"
Yes, it is very clever.
When creating the block, the ObjC compiler also specifies the Object stored
into the block metadata. When the block is copied (which is done as soon as
you call dispatch_async), the copied block retains these objects.
Note that it only works for blocks and ObjectiveC objects with some
(logical) special cases (ivars, __block).
See:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/bxVariables.html
--
Julien
On Fri, Jun 18, 2010 at 5:00 PM, Jonny Taylor <email@hidden>wrote:
> I've just been looking back at some code that has been working fine for me
> for a while, and as far as I can see it shouldn't actually work! I'd be
> interested for peoples' comments. The code is as follows:
>
> dispatch_async(queue1,
> ^{
> NSImage *theImage = [frame GetNSImage];
> NSData *tiffRep = [theImage TIFFRepresentation];
> dispatch_async(queue2,
> ^{
> [tiffRep writeToFile:[NSString stringWithFormat:@
> "%@%d.tif",
> [[frame Camera] ExportFilePrefix],
> [frame FrameNumber]]
> atomically:YES];
> });
> [theImage release];
> });
>
> Work running on serial queue "queue1" calculates a TIFF representation for
> an image, and then schedules work on serial queue "queue2" to write that
> data to disk. What I can't work out is why tiffrep isn't autoreleased as
> soon as the outer block completes. Is the compiler/runtime being clever
> enough to retain it because it is going to be needed in the inner block (if
> so: very clever!)? If not, am I just getting lucky here with exactly
> when/how grand central does its autorelease cleanup? Or maybe the TIFF
> representation and/or my frame data is still being retained elsewhere for a
> while (possible, depending on how the thread timings work out...).
>
> I'm pretty new to Cocoa so I'm keen to understand this properly - I'd be
> interested to hear peoples thoughts on this: is what I am doing ok, or do I
> need to add some explicit retain/releasing of tiffRep?
>
> Cheers
> Jonny_______________________________________________
>
> Cocoa-dev mailing list (email@hidden)
>
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>
> Help/Unsubscribe/Update your Subscription:
>
> This email sent to email@hidden
>
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden