views:

119

answers:

2

I use Core Foundation methods in garbage-collected environment. According to documentation call to CFRelease simply decrements reference count but does not release the object:

The difference between the garbage-collected environment and reference-counted environment is in the timing of the object’s deallocation. In a reference counted environment, when the object’s retain count drops to 0 it is deallocated immediately; in a garbage-collected environment, what happens when a Core Foundation object's retain count transitions from 1 to 0 depends on where it resides in memory:

  • If the object is in the malloc zone, it is deallocated immediately.
  • If the object is in the garbage collected zone, the last CFRelease() does not immediately free the object, it simply makes it eligible to be reclaimed by the collector when it is discovered to be unreachable—that is, once all strong references to it are gone. Thus as long as the object is still referenced from an object-type instance variable (that hasn't been marked as__weak), a register, the stack, or a global variable, it will not be collected.

Sometimes I open resource that is expensive to hold, e.g. file on the network:

CGImageSourceRef imageSource = CGImageSourceCreateWithURL(url, NULL);

Is it possible to deterministically release imageSource object (close, dispose, destroy, kill the bastard), without waiting for garbage collector?

.Net Framework has IDisposable interface and I can do this:

using (Font myFont = new Font("Arial", 10.0f))
{
    // use myFont
} // compiler will call Dispose on myFont

Is there something similar in Objective-C/Cocoa?

+1  A: 

First, CFImageSources are probably not allocated in the garbage-collected zone. So you're probably fine with simply releasing the last reference. (Mostly, only objects that originate from Objective-C are allocated in the garbage-collected zone.)

Second, if you want, you can simply download the data from the URL and open an image source from the data, if you need a guarantee that nothing will be open.

There's no direct equivalent to the IDisposable interface, but many types support being closed manually. CFImageSource isn't one of them, though.

John Calsbeek
+1  A: 

See Apple's docs on using CoreFoundation with garbage collection. TLDR version: Allocate the objects in kCFAllocatorMallocZone to exclude them from the garbage collection system.

Chuck
But how? CGImageSourceCreateWithURL has no alloc parameter.
Pavel Chuchuva