<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Tewha.net</title>
    <link>https://tewha.net/tags/debugging/</link>
    <description>Recent content on Tewha.net</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Wed, 06 Mar 2013 16:00:00 +0000</lastBuildDate>
    <atom:link href="https://tewha.net/tags/debugging/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Check your thread</title>
      <link>https://tewha.net/2013/03/check-your-thread/</link>
      <pubDate>Wed, 06 Mar 2013 16:00:00 +0000</pubDate>
      <guid>https://tewha.net/2013/03/check-your-thread/</guid>
      <description>&lt;p&gt;When you start using Grand Central Dispatch or &lt;code&gt;NSOperation&lt;/code&gt;, you’ll want to perform some actions on the main thread and some intentionally off the main thread.&lt;/p&gt;
&lt;p&gt;This is a simple and obvious technique, but it took me a while to adopt it: You can do by asserting with &lt;code&gt;NSAssert&lt;/code&gt; or &lt;code&gt;NSCAssert&lt;/code&gt; for &lt;code&gt;[NSThread isMainThread]&lt;/code&gt;, just as you would assert any other condition.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>When you start using Grand Central Dispatch or <code>NSOperation</code>, you’ll want to perform some actions on the main thread and some intentionally off the main thread.</p>
<p>This is a simple and obvious technique, but it took me a while to adopt it: You can do by asserting with <code>NSAssert</code> or <code>NSCAssert</code> for <code>[NSThread isMainThread]</code>, just as you would assert any other condition.</p>
<p>Like this:</p>
<pre><code>- (void)updateUI {
    NSAssert([NSThread isMainThread], @&quot;Only update UI from main thread&quot;);
    // update UI
}

- (void)backgroundWork {
    NSAssert(![NSThread isMainThread], @&quot;Only do work off main thread&quot;);
    // do work
}
</code></pre>
<p>With assertions like this in place, you’ll sort out what executes where in short order.</p>
<p>I wish I had done this to my code right away; it’s much simpler to get it right than to go back and fix it all later.</p>]]></content:encoded>
    </item>
    <item>
      <title>Presenting BlockAssert</title>
      <link>https://tewha.net/2013/02/presenting-blockassert/</link>
      <pubDate>Fri, 22 Feb 2013 16:00:00 +0000</pubDate>
      <guid>https://tewha.net/2013/02/presenting-blockassert/</guid>
      <description>&lt;p&gt;Assertions are a great tool. As an Objective-C programmer, I use &lt;code&gt;NSAssert&lt;/code&gt; and &lt;code&gt;NSCAssert&lt;/code&gt; liberally.&lt;/p&gt;
&lt;p&gt;For various reasons, you sometimes can’t use &lt;code&gt;NSAssert&lt;/code&gt; in a block easily. I’m going to explain why and describe a new macro, &lt;code&gt;BlockAssert&lt;/code&gt;, which solves this.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>Assertions are a great tool. As an Objective-C programmer, I use <code>NSAssert</code> and <code>NSCAssert</code> liberally.</p>
<p>For various reasons, you sometimes can’t use <code>NSAssert</code> in a block easily. I’m going to explain why and describe a new macro, <code>BlockAssert</code>, which solves this.</p>
<h2 id="background">Background</h2>
<p>An assertion is a predicate (a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place. (Source: <a href="http://en.wikipedia.org/wiki/Assertion_(computing)">Wikipedia</a>.)</p>
<p><code>NSAssert</code> and <code>NSCAssert</code> are Foundation’s assertion macros. They’re kind of like C’s assert macro, but provide an error message in the same form as <code>NSLog</code>. The difference between them is that <code>NSAssert</code> references <code>self</code>, which is only defined for Objective-C methods. <code>NSCAssert</code>, then, is <code>NSAssert</code> for C functions.</p>
<p>Blocks are often defined in Objective-C methods, but they’re not themselves Objective-C methods. Although they’re actually implemented as objects of their own, the syntax is more like a C functions. They don’t define self, though anything you want from the method scope are captured strongly into the block expression. This means that if you use <code>NSAssert</code> you’ll be capturing <code>self</code>. But that strong reference can cause a circular reference.</p>
<p>A circular reference is formed the block owns the object and the object owns something that owns the block. None of the memory will ever be cleaned up. Even you <em>do</em> clean up the memory, you’ll get a compiler warning that you need to ignore.</p>
<p>Rather than sort out which of these compiler warnings is valid, a lot of people use this pattern:</p>
<pre><code>__weak typeof(self) weakSelf = self;
foo.completionBlock = ^{
	__strong typeof(self) strongSelf = weakSelf;
    [strongSelf doSomething];
};
</code></pre>
<p>This breaks the circular reference, and because we’ve used <code>__weak</code> we’re assured that <code>weakSelf</code> is not a dangling pointer. If <code>self</code> no longer exists, <code>weakSelf</code> is <code>nil</code>. Reassigning back to a <code>__strong</code> variable presents the variable from being deallocated</p>
<p><em>In this case, it’s not actually necessary to assign <code>weakSelf</code> to a <code>__strong</code> variable. The recipient of a message won’t be deallocated until the message returns. However, if you are doing multiple things with <code>weakSelf</code> — such as doing assertions against it and sending it a message — it could become deallocated between those messages.</em></p>
<p>The catch? <code>NSAssert</code> still uses the <code>self</code> variable by name. This led to an interesting question on StackOverflow about <a href="http://stackoverflow.com/questions/14194600/is-typeofself-self-weakself-construction-legitimate-inside-block">defining a block-scope self</a>, a technique that’s valid but requires you to remember to do it every time and <a href="/2013/02/against-gcc_warn_shadow/">causes a warning if GCC_WARN_SHADOW is on</a>.</p>
<h2 id="a_new_assertion_macro">A new assertion macro</h2>
<p>In the past, I’ve mostly done avoided this by not using assertions in blocks. You don’t need them very often, as you can usually do your assertions in the method’s scope. But inspired by that question, I’ve found a better way: I define my own assertion macro.</p>
<p>I have several such macros I define, in a single file that’s imported in as part of my precompiled header.</p>
<p>The macro looks like this:</p>
<pre><code>#define BlockAssert(condition, desc, ...) 
    do { 
        __PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS 
        if (!(condition)) { 
            [[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd 
            object:strongSelf file:[NSString stringWithUTF8String:__FILE__] 
                lineNumber:__LINE__ description:(desc), ##__VA_ARGS__]; 
        } 
        __PRAGMA_POP_NO_EXTRA_ARG_WARNINGS 
    } while(0)
</code></pre>
<p>This is basically a copy-paste of <code>NSAssert</code>, but uses <code>strongSelf</code> instead of <code>self</code>. (Note, however, that we have <em>not</em> pretended to be part of Foundation by using a NS prefix.)</p>
<p>To use <code>BlockAssert</code>, you need to use the <code>weakSelf = self; strongSelf = weakSelf;</code> pattern, but you probably already are. And if not, the compiler will throw an error: <strong>Use of undeclared identifier: ‘strongSelf’</strong>. You can either adopt <code>strongSelf</code> or switch over to <code>NSAssert</code>.</p>
<p>For example:</p>
<pre><code>- (IBAction)clickButton: (UIButton *)sender {
    sender.disabled = YES;
    [self performActionWithCompletion: ^{
        BlockAssert(state, @&quot;Invalid state&quot;);
        sender.disabled = NO;
    }];
}
</code></pre>
<h2 id="conclusion">Conclusion</h2>
<p>I think this is a pretty good approach: If you use <code>NSAssert</code> where you meant to use <code>BlockAssert</code> and it matters, you’ll get a warning about a potential circular reference. If you use <code>BlockAssert</code> where you meant to use <code>NSAssert</code>, you’ll probably get a compiler error.</p>]]></content:encoded>
    </item>
  </channel>
</rss>
