× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Disallow Objective-C method calls with compile time errors via NS_UNAVAILABLE.

Joe Masilotti
Sep 21, 2014
<p>If you need a quick way to "block" method calls to your classes, the NS_UNAVAILABLE macro helps inform clients of your intentions.</p><p>Let's say you have a provider object that <em>needs</em> to be initialized with a delegate for proper use. You can use the macro to block calls to the <em>init</em> method to force the use of <em>initWithDelegate:</em>.</p><p>Bonus: Use the <em>@abstract</em> comment to explain the method that should be used instead.</p><pre><code class="language-objectivec">#import &lt;Foundation/Foundation.h&gt; @protocol LocationProviderDelegate; @interface LocationProvider : NSObject /*! @abstract Use initWithDelegate: to init with a delegate. */ - (instancetype)init NS_UNAVAILABLE; - (instancetype)initWithDelegate:(id&lt;LocationProviderDelegate&gt;)delegate; @end </code></pre><p>If someone trys to call the <em>init</em> method directly they will recieve a <strong>compile time</strong> error telling them a delegate must be provided.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus