Search code examples
objective-cmacosautomatic-ref-countingnsimage

Should I dealloc NSImage?


I am writing a simple Obj-c app. So far I've never had to alloc anything and I gave for granted that ARC would take care of memory management.

But now I have to call:

NSImage *myImage = [[NSImage alloc] initByReferencingFile: pathToMyImg];

After I'm done with myImage should I manually dealloc it?


Solution

  • If you’re using Objective-C ARC (which is the default, and you said you were anyway), there is no difference in required memory management between factory method-style instantiation and [[NSImage alloc] init]-style instantiation. Everything you create will be automatically released when the last strong reference goes out of scope (or the object holding the reference’s last strong reference goes out of scope).

    If you weren't using ARC, you’d have to manually do [myImage release] when you were done with it, but there’s no reason not to be unless you’re writing code for an older project.