title: Unit tests for memory management in Cocoa/Objective-C
body: <p>How would you write a unit test—using <a href="http://www.sente.ch/software/ocunit/" rel="noreferrer">OCUnit</a>, for instance—to ensure that objects are being released/retained properly in Cocoa/Objective-C?</p>
  <p>A naïve way to do this would be to check the value of <code>retainCount</code>, but of course <em><a href="https://stackoverflow.com/questions/4636146/when-to-use-retaincount/4636477#4636477">you should never use <code>retainCount</code></a></em>. Can you simply check whether an object's reference is assigned a value of <code>nil</code> to indicate that it has been released? Also, what guarantees do you have about the timing at which objects are actually deallocated?</p>
  <p>I'm hoping for a concise solution of only a few lines of code, as I will probably use this extensively. There may actually be two answers: one that uses the autorelease pool, and another that does not.</p>
  <p>To clarify, <em>I'm not looking for a way to comprehensively test every object that I create.</em> It's impossible to unit test <em>any</em> behavior comprehensively, let alone memory management. At the very least, though, it would be nice to check the behavior of released objects for regression testing (and ensure that the same memory-related bug doesn't happen twice).</p>
  <h2>About the Answers</h2>
  <p>I accepted <a href="https://stackoverflow.com/users/100478/bj-homer">BJ Homer</a>'s <a href="https://stackoverflow.com/questions/6576312/unit-tests-for-memory-management-in-cocoa-objective-c/6585640#6585640">answer</a> because I found it to be the easiest, most concise way of accomplishing what I had in mind, given the caveat that the weak pointers provided with <a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html" rel="noreferrer">Automatic Reference Counting</a> aren't available in production versions of XCode (prior to 4.2?) as of July 23rd, 2011. I was also impressed to learn that</p>
  <blockquote>
  <p>ARC can be enabled on a per-file basis; it does not require that your
  entire project use it. You could compile your unit tests with ARC and
  leave your main project on manual retain-release, and this test would
  still work.</p>
  </blockquote>
  <p>That being said, for a far more detailed exploration of the potential issues involved with unit testing memory management in Objective-C, I highly recommend <a href="https://stackoverflow.com/users/30461/peter-hosey">Peter Hosey</a>'s <a href="https://stackoverflow.com/questions/6576312/unit-tests-for-memory-management-in-cocoa-objective-c/6580824#6580824">in-depth response</a>.</p>