Search code examples
objective-cautoreleasensbundle

How do you use NSBundle pathForResource without autorelease pool?


What is the non-autorelease equivalent of this code?

NSString *nsFName = [[NSBundle mainBundle] pathForResource:nsName ofType:nsExt inDirectory:nsPath];


Solution

  • There isn't one. When you're using Cocoa, you must have a pool in place:

    Cocoa always expects there to be an autorelease pool available. If a pool is not available, autoreleased objects do not get released and your application leaks memory. If you send an autorelease message when a pool is not available, Cocoa logs a suitable error message.

    Part of the GUI application set-up process is establishing one on the main thread; non-GUI programs need to create one as well.

    If you're creating your own threads, you need to create and manage an autorelease pool for each of those threads as well:

    Applications that link in Objective-C frameworks typically must create at least one autorelease pool in each of their threads. If an application uses the managed model—where the application handles the retaining and releasing of objects—the autorelease pool catches any objects that are autoreleased from that thread.

    Depending on what else you are doing, you may be able to use CoreFoundation. There's a CFType, CFBundle, on which NSBundle is built. It has a function CFBundleCopyResourceURL() that may do what you need. If you can translate all your code to Core Foundation, then you can escape using a pool, although -- as Ken says -- it's really not the burden that you think it is. You're probably hitting the disk every time you use pathForResource:ofType: anyways.