<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" 
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:admin="http://webns.net/mvcb/"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:content="http://purl.org/rss/1.0/modules/content/">

  <channel>
    <title>Dave Dribin&apos;s Blog</title>
    <link>http://www.dribin.org/dave/blog/</link>
    <description></description>
    <dc:language>en-us</dc:language>
    <dc:creator>dave@dribin.org</dc:creator>
    <dc:rights>Copyright 2011</dc:rights>
    <dc:date>2011-04-05T21:12:04-06:00</dc:date>
    <admin:generatorAgent rdf:resource="http://www.movabletype.org/?v=4.1" />
    <admin:errorReportsTo rdf:resource="mailto:dave@dribin.org"/>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <sy:updateBase>2000-01-01T12:00+00:00</sy:updateBase>


    <item>
      <title>My Unit Testing C4[3] Presentation</title>
      <link>http://www.dribin.org/dave/blog/archives/2011/04/05/unit_test_c4/</link>
      <description>I should have posted this literally years ago. Since I just learned that Keynote can easily publish presentations to iWork.com, I figure I have no excuse. Thus, here&#8217;s my C4[3] presentation on unit testing: [Direct Link]...</description>
      <guid isPermaLink="false">435@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>I should have posted this literally years ago.  Since I just learned that Keynote can easily publish presentations to <a href="http://www.iwork.com/">iWork.com</a>, I figure I have no excuse.  Thus, here&#8217;s my C4[3] presentation on unit testing:</p>

<iframe frameborder='0' style='width:460px;height:375px;' src='http://public.iwork.com/embed/?d=UnitTesting-C4[3].key&a=p24449714&h=768&w=1024&sw=458'></iframe>

<p>[<a href="http://drib.in/UnitTesting-C4-3">Direct Link</a>]</p>
 
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2011-04-05T21:12:04-06:00</dc:date>
    </item>

    <item>
      <title>Joining Apple</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/10/01/joining_apple/</link>
      <description>Next week, I fly out to Cupertino to start working at Apple as a full time employee. This is a big move for me, as I&#8217;ve been working for myself since 2001. But this is truly a once-in-a-lifetime opportunity that...</description>
      <guid isPermaLink="false">434@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>Next week, I fly out to Cupertino to start working at <a href="http://www.apple.com/">Apple</a> as a full time employee.  This is a big move for me, as I&#8217;ve been working for myself since 2001.  But this is truly a once-in-a-lifetime opportunity that I cannot pass up.  As is the case for a lot of people my age, I began my computing experience on an <a href="http://en.wikipedia.org/wiki/Apple_II_series">Apple ][</a> and have been a huge fan of Apple ever since (with a slight defection to Linux in the late 90s and early 00s).  Apple-related technology (Mac OS X and iOS) has been my main source of income since around 2006, so in many ways, this is a dream come true.  I&#8217;m very excited to work with a great team and for a great company.</p>
 <p>Because everything needs an FAQ:</p>

<h3>What will you be working on?</h3>

<p>I&#8217;m not sure that I can say, just yet. But it will involve heavy amounts of coding in Objective-C.</p>

<h3>So you&#8217;re moving to California?</h3>

<p>Nope.  I&#8217;ll be staying right here in Chicago.</p>

<h3>Will you still be writing The Road to Code for MacTech Magazine?</h3>

<p>Unfortunately, I will be unable to continue writing <em>The Road to Code</em> for <a href="http://www.mactech.com/">MacTech</a>, and I&#8217;ve already submitted my last article.  It has been an amazing <a href="http://www.dribin.org/dave/blog/archives/2007/07/05/road_to_code/">three years</a>, and I am truly grateful to have worked with MacTech.</p>

<h3>What about public speaking?</h3>

<p>I will also be unavailable for future speaking engagements.  I&#8217;ve already had to turn down opportunities to speak at <a href="http://www.voicesthatmatter.com/">Voices that Matter</a>, the <a href="http://www.mactech.com/conference/about">MacTech conference</a>, and <a href="http://www.secondconf.com/">SecondConf</a>.  I&#8217;m sure I will be an attendee at a number of the conferences, though, and I plan to stay active in the community as much as possible.</p>

<h3>What does this mean for Bit Maki and Textcast?</h3>

<p>This is still preliminary and in progress, but Bit Maki Software, Inc., the joint company between <a href="http://rentzsch.tumblr.com/">Jonathan Rentzsch</a> and I, is in process of being dissolved.  I plan to keep Bit Maki, Inc., my contracting company, alive for now, though I will not be doing any more contracting.  <a href="http://www.bitmaki.com/textcast/">Textcast</a> will become free and be available from the Bit Maki website.</p>

<h3>What&#8217;s the future of MAME OS X?</h3>

<p>It has been a few  years since I&#8217;ve been able to dedicate much time towards <a href="http://mameosx.sourceforge.net/">MAME OS X,</a> and this is the nail in the coffin.  I will not be able to contribute to MAME OS X.  If anyone want&#8217;s to pick up the effort, please <a href="http://www.dribin.org/dave/contact/">let me know</a>.  This also goes for most of my other <a href="http://www.dribin.org/dave/software/">open source software</a>.  Truth be told, with <a href="http://www.dribin.org/dave/blog/archives/2010/09/16/lily_and_zach/">the two recent additions to our family</a>, I&#8217;m going to be sufficiently distracted for a while, anyways.</p>
]]>
      </content:encoded>
      <dc:subject>Personal</dc:subject>
      <dc:date>2010-10-01T18:09:19-06:00</dc:date>
    </item>

    <item>
      <title>Welcome Lily and Zach Dribin</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/09/16/lily_and_zach/</link>
      <description>My wife and I recently brought home two new additions to the Ross-Dribin family: Lily and Zach! All four of us are doing great, but everything since then has been a blur....</description>
      <guid isPermaLink="false">433@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>My wife and I recently brought home two new additions to the Ross-Dribin family: Lily and Zach! All four of us are doing great, but everything since then has been a blur.</p>

<p><img src="http://www.dribin.org/dave/resources/images/2010/lily_and_zach.jpg" width="640" height="427" /></p>
 
]]>
      </content:encoded>
      <dc:subject>Personal</dc:subject>
      <dc:date>2010-09-16T22:04:51-06:00</dc:date>
    </item>

    <item>
      <title>trigint: An Integer-based Trigonometry Library</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/08/15/announcing_trigint/</link>
      <description>Back when I was writing the A440 sample code for my iPad Dev Camp presentation, I needed to generate a 440 Hz sine wave. The simplest way to do this is to use the sin() or sinf() standard C library...</description>
      <guid isPermaLink="false">432@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>Back when I was writing the <a href="http://www.dribin.org/dave/blog/archives/2010/04/26/announcing_a440/">A440 sample code</a> for my <a href="http://www.dribin.org/dave/blog/archives/2010/05/02/ipad_dev_camp_slides/">iPad Dev Camp presentation</a>, I needed to generate a 440 Hz sine wave.  The simplest way to do this is to use the sin() or sinf() standard C library functions.  But there was one minor caveat: these functions required using floating point data types.  However, floating point on the iPhone hardware is (or at least was) not that fast compared to integer calculations, especially when compiled in Thumb mode, which is the default.  You could disable Thumb mode, but then the code size would be ~35% larger.</p>

<p>Or, you could avoid floating point altogether.  Thus, I wrote trigint, a 100% integer-based trigonometry library.  It uses a 16-entry lookup table plus <a href="http://en.wikipedia.org/wiki/Linear_interpolation">linear interpolation</a> so it&#8217;s quite memory efficient, yet still <a href="http://www.dribin.org/dave/trigint/accuracy.html">accurate</a> enough for most purposes. Since it&#8217;s written in ANSI C99, it can be used on 8-bit microcontrollers, like an <a href="http://www.atmel.com/products/avr/">Atmel AVR</a> with <a href="http://www.avrfreaks.net/wiki/index.php/Documentation:AVR_GCC">avr-gcc</a>.  Here&#8217;s the <a href="http://bitbucket.org/ddribin/trigint">code</a> and the <a href="http://www.dribin.org/dave/trigint/">API documentation</a>.</p>

<p>How fast is it? Take a look at the <a href="http://www.dribin.org/dave/trigint/performance-ios.html">numbers on a 1st generation iPod Touch</a>.  In summary, trigint_sin16() is about 4.4 times faster than sinf() and 6.7 times faster than sin() in Thumb mode. Without Thumb mode, the gap closes a bit to 3.8 times faster and 6.2 times faster, respectively.  I haven&#8217;t, yet run the benchmark on the iPhone 4 or the iPad, so it may not matter as much on the more modern hardware; however, it&#8217;s still useful for the the 8-bit MCUs like the AVR, though.</p>

<p>trigint is essentially a C version of the Scott Dattalo&#8217;s <a href="http://www.dattalo.com/technical/software/pic/picsine.html">sine wave routine for the PIC microcontroller</a>. Credit goes to Scott for coming up with the algorithm. He&#8217;s also got a whole write up of <a href="http://www.dattalo.com/technical/theory/sinewave.html">sine wave theory</a>. Scott is one of the most brilliant assembly coders I&#8217;ve ever run into.  He <a href="http://www.dattalo.com/technical/software/pic/crc_8005.asm">helped me </a>optimize a <a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check">CRC-16</a> routine in <a href="http://www.dattalo.com/technical/software/pic/crc.php">PIC assembly</a>, years ago.</p>
 
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2010-08-15T10:06:26-06:00</dc:date>
    </item>

    <item>
      <title>My Chiptune Cover of Don&apos;t Stop Believin&apos;</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/07/18/dont_stop/</link>
      <description>Here&#8217;s a chiptune cover of Journey&#8217;s Don&#8217;t Stop Believin&#8217; I made during some time off I had last December. I just haven&#8217;t gotten around to posting it until now (though I did make a few tweaks yesterday). I think we...</description>
      <guid isPermaLink="false">431@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>Here&#8217;s a <a href="http://en.wikipedia.org/wiki/Chiptune">chiptune</a> cover of Journey&#8217;s <em>Don&#8217;t Stop Believin&#8217;</em> I made during some time off I had last December.  I just haven&#8217;t gotten around to posting it until now (though I did make a few tweaks yesterday).  I think we were watching Glee at the time and remember thinking a chiptune version would be even better than theirs.  It was made with <a href="http://famitracker.shoodot.net/">FamiTracker</a>, and this video is of the song being played in FamiTracker:</p>

<p><object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/LZBo4vLguOA&amp;hl=en_US&amp;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/LZBo4vLguOA&amp;hl=en_US&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object></p>

<p>You can listen to and download the MP3 from <a href="http://8bc.org/music/ddribin/Don%27t+Stop+Believin%27+%28NES+Remake%29/">its 8bitcollective page</a>.  Or download <a href="http://www.dribin.org/dave/resources/files/2010/Don%27t%20Stop%20Believin%27.nsf">the NSF</a> (<a href="http://en.wikipedia.org/wiki/NES_Sound_Format">what&#8217;s an NSF?</a>) and play it in an NSF player, such as my own <a href="http://bitbucket.org/ddribin/chip-player">Chip Player</a>. Or perhaps something a bit more stable like <a href="http://www.bannister.org/software/ao.htm">Audio Overload</a>.</p>
 
]]>
      </content:encoded>
      <dc:subject>Music</dc:subject>
      <dc:date>2010-07-18T09:27:17-06:00</dc:date>
    </item>

    <item>
      <title>Fun with C99 Syntax</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/05/15/c99_syntax/</link>
      <description>The C99 language added some pretty neat features to the ANSI C we know and love (now known as C89). I used a construct called compound literals in my iPad Dev Camp presentation, and it seemed new to a lot...</description>
      <guid isPermaLink="false">430@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>The <a href="http://en.wikipedia.org/wiki/C99">C99</a> language added some pretty neat features to the ANSI C we know and love (now known as C89).  I used a construct called <a href="http://www.drdobbs.com/cpp/184401404">compound literals</a> in my <a href="http://www.dribin.org/dave/blog/archives/2010/05/02/ipad_dev_camp_slides/">iPad Dev Camp presentation</a>, and it seemed new to a lot of people.  Here&#8217;s a summary of some lesser know features about C99 that are worth knowing.  And, since Objective-C is a strict superset of C, all this applies to Objective-C, as well.  Best of all, as of recent Xcode (3.0? 3.1?), C99 is the default C dialect for new projects, so you don&#8217;t need to do anything to start taking advantage of these.</p>
 <h3>Structure Initialization</h3>

<p>Structure initialization received a lot of love in C99.  In C89, you could initialize a structure variable like this:</p>

<pre><code>NSPoint point = {0, 0};
</code></pre>

<p>The caveat here is that the structure elements must be provided in the order that they are listed in the definition.  In this case, <code>NSPoint</code> is declared as like:</p>

<pre><code>typedef struct _NSPoint {
    CGFloat x;
    CGFloat y;
} NSPoint;
</code></pre>

<p>So, when we initialize a variable, <code>x</code> comes first, followed by <code>y</code>.  This can be a drawback because if the order in the definition ever changed, all existing code that depended on the order would break. As of C99, you can initialize a structure by specifying the structure element names:</p>

<pre><code>NSPoint point = { .x = 0, .y = 0};
</code></pre>

<p>This not only decouples the order of the definition from the order of the initialization, but it&#8217;s more readable.  As an added benefit, any structure elements not initialized are set to zero.  This means you only need to fill out the portions of the structure that are relevant.  And if new elements to the structure are added in later versions, they get initialized to a known value.</p>

<p>The benefit of this becomes even more clear for nested structures like <code>NSRect</code>:</p>

<pre><code>typedef struct _NSRect {
    NSPoint origin;
    NSSize size;
} NSRect;
</code></pre>

<p>To initialize an <code>NSRect</code> in straight C89 looked something like this:</p>

<pre><code>NSRect rect = {{0, 0}, {640, 480}};
</code></pre>

<p>Because this is kind of awkward, there&#8217;s a function to make this a bit easier:</p>

<pre><code>NSRect rect = NSMakeRect(0, 0, 640, 480);
</code></pre>

<p>But, honestly, that&#8217;s not much of an improvement in readability.  <code>NSMakeRect</code> is more useful in structure assignment, but we&#8217;ll see an alternate way to do this below.  With C99, we can initialize this variable like:</p>

<pre><code>NSRect rect = {
    .origin.x = 0,
    .origin.y = 0,
    .size.width = 640,
    .size.height = 480,
};
</code></pre>

<p>Again, we can order the structure elements however we please; we&#8217;re not required to list them in the order of the definition.  We have some flexibility in how we assign the nested structures, too.  This is also legal:</p>

<pre><code>NSRect rect = {
    .origin = {.x = 0, .y = 0},
    .size = {.width = 640, .height = 480},
};
</code></pre>

<p>As as this:</p>

<pre><code>NSRect rect = {
    .origin = NSMakePoint(0, 0),
    .size = NSMakeSize(640, 480),
};
</code></pre>

<p>And even this:</p>

<pre><code>NSRect rect = {
    .origin = otherRect.origin,
    .size = NSMakeSize(640, 480),
};
</code></pre>

<p>So, as you can see, we get a lot more flexibility on how to initialize structures.</p>

<h3>Compound Literals for Structure Assignment</h3>

<p>This new syntax of initializing structure variables is great, but it doesn&#8217;t help us much for assigning to existing structure variables.  The example I used in my iPad Dev Camp talk was setting up a <code>AudioStreamBasicDescription</code> structure, colloquially known as <code>ASBD</code>.  This structure is used to describe an audio format for <a href="http://developer.apple.com/mac/library/documentation/MusicAudio/Conceptual/CoreAudioOverview/Introduction/Introduction.html">Core Audio</a>.  In this case, I had an <code>ASBD</code> instance variable.  Because it&#8217;s an instance variable, you cannot set its value using the initialization syntax above.  Thus, the traditional way to initialize one of these it to clear out it to zero with <code>memset</code>, and then set the fields you need, one by one:</p>

<pre><code>memset(&amp;_dataFormat, 0, sizeof(_dataFormat));
_dataFormat.mFormatID = kAudioFormatLinearPCM;
_dataFormat.mSampleRate = SAMPLE_RATE;
_dataFormat.mBitsPerChannel = 16;
// And on and on...
</code></pre>

<p>Using new C99 syntax known as a <a href="http://www.drdobbs.com/cpp/184401404">compound literal</a>, you can set an existing structure variable like this:</p>

<pre><code>_dataFormat = (AudioStreamBasicDescription) {
    .mFormatID = kAudioFormatLinearPCM,
    .mSampleRate = SAMPLE_RATE,
    .mBitsPerChannel = 16,
    // And on and on...
};
</code></pre>

<p>It looks similar to a cast plus an initialization.  And under the hood, the compiler is making a anonymous variable.  So you can think of the above as equivalent to:</p>

<pre><code>AudioStreamBasicDescription anon = {
    .mFormatID = kAudioFormatLinearPCM,
    .mSampleRate = SAMPLE_RATE,
    .mBitsPerChannel = 16,
    // And on and on...
};
_dataFormat = anon;
</code></pre>

<p>Again, the nice thing here as that unset fields are initialized to zero, so you get the equivalent of the <code>memset</code>.  Plus, you don&#8217;t have to repeat the variable name over and over again.</p>

<p>Oh, and as a quick shorthand for setting the entire structure to zero, you can do something like this:</p>

<pre><code>_dataFormat = (AudioStreamBasicDescription) {0};
</code></pre>

<h3>Compound Literals with Primitives</h3>

<p>Compound literals can be applied to primitive types, too.  Most of the time this is not much use:</p>

<pre><code>int i = (int) {3};
</code></pre>

<p>But because these are anonymous variables, you can take the address of them:</p>

<pre><code>int * iPointer = &amp;(int) {3};
</code></pre>

<p>This can be useful for some Core Audio APIs, such as <code>AudioUnitSetProperty</code>.  Typically you create a variable for the sole purpose of taking the address of it:</p>

<pre><code>UInt32 maxFramesPerSlice = 4096;
AudioUnitSetProperty(converterAudioUnit,
                     kAudioUnitProperty_MaximumFramesPerSlice,
                     kAudioUnitScope_Global,
                     0,
                     &amp;maxFramesPerSlice,
                     sizeof(UInt32));
</code></pre>

<p>Using compound literals, we can do this inline without an extra variable:</p>

<pre><code>AudioUnitSetProperty(converterAudioUnit,
                     kAudioUnitProperty_MaximumFramesPerSlice,
                     kAudioUnitScope_Global,
                     0,
                     &amp;(UInt32) {4096},
                     sizeof(UInt32));
</code></pre>

<h3>Conclusion</h3>

<p>While C99 was a relatively minor update to C89, there are quite a few gems buried away to make our code more flexible and readable, as you can see.</p>
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2010-05-15T08:52:20-06:00</dc:date>
    </item>

    <item>
      <title>iPad Dev Camp Slides</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/05/02/ipad_dev_camp_slides/</link>
      <description>First off, a big thanks to David Kinney (@dlkinney) for organizing this year&#8217;s iPad Dev Camp Chicago. Here are the slides to my Core Audio presentations: Audio Queue Services Audio Unit Graphs The source code to the two projects I...</description>
      <guid isPermaLink="false">429@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>First off, a big thanks to David Kinney (<a href="http://twitter.com/dlkinney">@dlkinney)</a> for organizing this year&#8217;s <a href="http://ipaddevcampchi.wordpress.com/">iPad Dev Camp Chicago</a>.  Here are the slides to my Core Audio presentations:</p>

<ul>
<li><a href="http://www.dribin.org/dave/resources/files/2010/ipdcchi_Dribin_AudioQueue.pdf">Audio Queue Services</a></li>
<li><a href="http://www.dribin.org/dave/resources/files/2010/ipdcchi_Dribin_AudioUnits.pdf">Audio Unit Graphs</a></li>
</ul>

<p>The source code to the two projects I went over are up on <a href="http://bitbucket.org/ddribin">BitBucket</a>:</p>

<ul>
<li><a href="http://bitbucket.org/ddribin/a440/wiki/Home">A440</a>: A Core Audio &#8220;Hello World&#8221;. Runs on Mac, iPhone, and iPad.</li>
<li><a href="http://bitbucket.org/ddribin/chip-player">Chip Player</a>: A chiptune player using the <a href="http://www.fly.net/~ant/libs/audio.html">Game Music Emu</a> library.  Runs on Mac and iPad and plays popular chiptune file formats, such as <a href="http://en.wikipedia.org/wiki/NES_Sound_Format">NSF</a> and <a href="http://en.wikipedia.org/wiki/Game_Boy_Sound_System">GBS</a>.</li>
</ul>

<p>Use the <code>ipaddevcamp2010</code> tag to see what they looked like at the time of the presentations.</p>
 
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2010-05-02T23:11:00-06:00</dc:date>
    </item>

    <item>
      <title>A440: A Core Audio &quot;Hello World&quot;</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/04/26/announcing_a440/</link>
      <description>iPad Dev Camp Chicago is coming up this weekend, and I&#8217;m going to be giving two talks about Core Audio. One of the applications we are going to go over is called A440, a &#8220;Hello World&#8221; of Core Audio. It...</description>
      <guid isPermaLink="false">428@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p><a href="http://ipaddevcampchi.wordpress.com/">iPad Dev Camp Chicago</a> is coming up this weekend, and I&#8217;m going to be giving two talks about <a href="http://developer.apple.com/iphone/library/documentation/MusicAudio/Conceptual/CoreAudioOverview/Introduction/Introduction.html">Core Audio</a>.  One of the applications we are going to go over is called A440, a &#8220;Hello World&#8221; of Core Audio.  It plays a simple a <a href="http://en.wikipedia.org/wiki/A440">440 Hz tone</a> using both <a href="http://developer.apple.com/mac/library/documentation/MusicAudio/Reference/AudioQueueReference/Reference/reference.html">Audio Queue Services</a> (AudioQueueRef and friends) and <a href="http://developer.apple.com/mac/library/documentation/AudioToolbox/Reference/AUGraphServicesReference/Reference/reference.html">Audio Unit Processing Graph Services</a> (AUGraph and friends).  In order to keep the code as simple as possible, it does not use any of the &#8220;Public Utility&#8221; C++ APIs.</p>

<p>I&#8217;ve posted the code up <a href="http://bitbucket.org/ddribin/a440/">on BitBucket</a> if you want to check it out before hand or are unable to attend.  I also hope to have a more complex and complete audio playing application ready to release by this weekend, too.  Hint, it&#8217;ll have something to do with <a href="http://en.wikipedia.org/wiki/Chiptune">8-bit chiptunes</a>.  So if you&#8217;re in Chicago, <a href="http://ipaddevcampchi.wordpress.com/register/">sign up</a>!  It&#8217;ll be fun!</p>
 
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2010-04-26T09:00:49-06:00</dc:date>
    </item>

    <item>
      <title>Debugging Asynchronous performSelector: Calls</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/03/19/debugging_async_perform_selector/</link>
      <description>This afternoon, I had to debug an issue that involved performSelectorOnMainThread:. This method is a great way to get a background thread to safely interact with the user interface. But when you set a breakpoint or crash nested down in...</description>
      <guid isPermaLink="false">427@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>This afternoon, I had to debug an issue that involved <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorOnMainThread:withObject:waitUntilDone:"><code>performSelectorOnMainThread:</code></a>. This method is a great way to get a background thread to safely interact with the user interface.  But when you set a breakpoint or crash nested down in one of these method calls, sometimes it&#8217;s useful to get a backtrace of who called <code>performSelectorOnMainThread:</code>.  Unfortunately, by the time our method gets called, we don&#8217;t have that information.  The same goes for <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelector:withObject:afterDelay:"><code> performSelector:withObject:afterDelay:</code></a>.</p>

<p>After some good suggestions on Twitter, and a bit of <strike>casual</strike> <a href="http://twitter.com/ddribin/status/10778596555">recreational</a> coding, I&#8217;ve come up with a general purpose solution that involves, of course, <a href="http://www.cocoadev.com/index.pl?MethodSwizzling">method swizzling</a>.</p>
 <p>Take this code in an application delegate as an example:</p>

<pre>
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self performSelectorOnMainThread:@selector(echo:) withObject:@"foo" waitUntilDone:NO];
    });

    [self performSelector:@selector(echo:) withObject:@"bar" afterDelay:3.0];
}

- (void)echo:(id)object
{
    NSLog(@"echo: %@", object);
}
</pre>

<p>If you set a breakpoint in the <code>echo:</code> method, you&#8217;ll see a backtrace like:</p>

<pre>
(gdb) bt
#0  -[PerformDebugAppDelegate echo:] (self=0x10012c480, _cmd=0x100002462, object=0x1000030e8) at /Users/dave/Desktop/PerformDebug/PerformDebugAppDelegate.m:42
#1  0x00007fff83500647 in __NSThreadPerformPerform ()
#2  0x00007fff80477271 in __CFRunLoopDoSources0 ()
#3  0x00007fff80475469 in __CFRunLoopRun ()
#4  0x00007fff80474c2f in CFRunLoopRunSpecific ()
#5  0x00007fff8101ea4e in RunCurrentEventLoopInMode ()
#6  0x00007fff8101e7b1 in ReceiveNextEventCommon ()
#7  0x00007fff8101e70c in BlockUntilNextEventMatchingListInMode ()
#8  0x00007fff870b21f2 in _DPSNextEvent ()
#9  0x00007fff870b1b41 in -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] ()
#10 0x00007fff87077747 in -[NSApplication run] ()
#11 0x00007fff87070468 in NSApplicationMain ()
#12 0x0000000100001a09 in main (argc=1, argv=0x7fff5fbff1f0) at /Users/dave/Desktop/PerformDebug/main.m:29
</pre>

<p>This really isn&#8217;t all that helpful.  Yes, <code>echo:</code> was called, but we don&#8217;t know who called it.  If <code>echo:</code> is a method that tends to get called from a number of places with a <code>performSelector...</code> variant, we don&#8217;t know which one it is.</p>

<p>This afternoon, I took the easy way out, and set an auto-continuing breakpoint on <code>-[NSObject performSelector:onThread:withObject:waitUntilDone:modes:]</code> with a <code>bt</code> action.  This isn&#8217;t ideal, though.  First, this method gets called quite a bit, so hitting the breakpoint can slow things down a lot.  Plus, it dumps the stack trace for each call, cluttering the gdb console with mostly useless garbage.</p>

<p>The breakpoint actually helped me debug the issue today, but I&#8217;ve run into this situation a number of times in the past and never had a good way to debug it.  Until now.</p>

<h3>Swizzling for Fun and Profit</h3>

<p>The key is to swizzle the <code>NSObject</code> implementations of these two methods:</p>

<ul>
<li><code>performSelector:withObject:afterDelay:inModes:</code></li>
<li><code>performSelector:onThread:withObject:waitUntilDone:modes:</code></li>
</ul>

<p>In our swizzled implementations, we&#8217;d like to capture the backtrace at time they are called.  Later, we can dump out the backtrace for debugging, if we want to.  To do this, we&#8217;ll create an intermediate object to hold the backtrace: <code>DDPerformDebugger</code>.  Here are its two most important methods:</p>

<pre>
- (id)initWithTarget:(id)target selector:(SEL)selector argument:(id)argument;
{
    self = [super init];
    if (self == nil)
        return nil;

    _target = [target retain];
    _selector = selector;
    _argument = [argument retain];
    // Capture a backtrace at the time we're created
    _frames = backtrace(_callstack, sizeof(_callstack)/sizeof(*_callstack));

    return self;
}

- (void)perform;
{
    [_target performSelector:_selector withObject:_argument];
}
</pre>

<p>In the initializer, we capture the target, selector, and argument.  But we also capture a backtrace using the very handy <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/backtrace.3.html">backtrace(3)</a> function.</p>

<p>In our swizzled <code>performSelector...</code>, we create an instance of <code>DDPerformDebugger</code>, but instead of passing the target and selector to the original implementation, we use this instance as the target and <code>perform</code> as the selector.  As you can see above, this just forwards it on to the passed in target and selector.  However, as I demonstrate below, we&#8217;ll have access to the saved backtrace.  Here&#8217;s what the swizzled method looks like:</p>

<pre>
- (void)dd_performSelector:(SEL)selector withObject:(id)argument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes;
{
    DDPerformDebugger * debugger = [[DDPerformDebugger alloc] initWithTarget:self
                                                                    selector:selector
                                                                    argument:argument];
    [debugger autorelease];

    // This calls the original implementation.  It's not recursing.
    [debugger dd_performSelector:@selector(perform)
                      withObject:nil
                      afterDelay:delay
                         inModes:modes];
}
</pre>

<p>The swizzled <code>dd_performSelectorOnMainThread:...</code> looks similar.  Now, when we stop on our breakpoint in <code>echo:</code>, we get the following backtrace:</p>

<pre>
(gdb) bt 5
#0  -[PerformDebugAppDelegate echo:] (self=0x10012b170, _cmd=0x100002462, object=0x1000030e8) at /Users/dave/Desktop/PerformDebug/PerformDebugAppDelegate.m:42
#1  0x000000010000207c in -[DDPerformDebugger perform] (self=0x10101ae00, _cmd=0x7fff85a42a1a) at /Users/dave/Desktop/PerformDebug/DDPerformDebugger.m:157
#2  0x00007fff83500647 in __NSThreadPerformPerform ()
#3  0x00007fff80477271 in __CFRunLoopDoSources0 ()
#4  0x00007fff80475469 in __CFRunLoopRun ()
(More stack frames follow...)
</pre>

<p>This isn&#8217;t much help on it&#8217;s own.  But if we jump to frame 1, where we&#8217;re inside the <code>perform</code> method of our intermediate object, we have access to the backtrace of the original calling point.  I&#8217;ve rigged up the <code>description</code> method to show the backtrace, so it&#8217;s easy to get:</p>

<pre>
(gdb) po self
&lt;DDPerformDebugger 0x10101ae00: target: &lt;PerformDebugAppDelegate 0x10012b170&gt;, selector: &lt;echo:&gt;, argument: &lt;NSCFString 0x1000030e8&gt;
0   PerformDebug                        0x0000000100001f45 -[DDPerformDebugger initWithTarget:selector:argument:] + 268
1   PerformDebug                        0x0000000100001d3c -[NSObject(DDPerformDebugger) dd_performSelector:onThread:withObject:waitUntilDone:modes:] + 99
2   Foundation                          0x00007fff83512d54 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:] + 143
3   PerformDebug                        0x0000000100001b42 __-[PerformDebugAppDelegate applicationDidFinishLaunching:]_block_invoke_1 + 66
4   libSystem.B.dylib                   0x00007fff86eebce8 _dispatch_call_block_and_release + 15
5   libSystem.B.dylib                   0x00007fff86eca279 _dispatch_worker_thread2 + 231
6   libSystem.B.dylib                   0x00007fff86ec9bb8 _pthread_wqthread + 353
7   libSystem.B.dylib                   0x00007fff86ec9a55 start_wqthread + 13
</pre>

<p>We can see we&#8217;re on on a GCD thread inside <code>applicationDidFinishLaunching:</code>.  The only downside to the <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/backtrace.3.html">backtrace_symbols(3)</a> function is that it does not utilize debugging information to show line numbers.  We just get an offset into the method.</p>

<p>Fortunately, a command line tool called <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/atos.1.html">atos(1)</a> can provide us with this information.  Given an address, it&#8217;ll decode the symbol <em>and</em> line number information. We can even invoke this right from inside gdb:</p>

<pre>
(gdb) info pid
Inferior has process ID 11017.
(gdb) shell atos -p 11017 0x0000000100001b42
__-[PerformDebugAppDelegate applicationDidFinishLaunching:]_block_invoke_1 (in PerformDebug) (PerformDebugAppDelegate.m:35)
</pre>

<p>And know we know that <code>performSelectorOnMainThread:</code> was originally called from line 35 of PerformDebugAppDelegate.m.  Very helpul!</p>

<p>The full code for <code>DDPerformDebugger</code> is part of my <a href="http://bitbucket.org/ddribin/ddfoundation/">DDFoundation</a> project on BitBucket, but you can grab just the <a href="http://bitbucket.org/ddribin/ddfoundation/src/d41050234d53/lib/DDPerformDebugger.m">one file</a> on its own and and included it with your project.  By default, it does not swizzle anything, so you can compile it in for every build and not worry about taking a performance hit creating those intermediate objects.  To enable the swizzling, just set the <code>DDPerformDebug</code> environment variable to <code>YES</code>.  Grab a sample project, <a href="http://www.dribin.org/dave/resources/files/2010/PerformDebug.tgz">PerformDebug.tgz</a>, and try it out for yourself.</p>
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2010-03-19T23:42:49-06:00</dc:date>
    </item>

    <item>
      <title>What I Miss from Java</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/03/02/what_i_miss_from_java/</link>
      <description>On Monday, I had a series of tweets ([1], [2], [3]) about what I like about Java that I miss in Objective-C/Cocoa that were probably better off in a blog post. I blame Jeff LaMarche for baiting me into the...</description>
      <guid isPermaLink="false">426@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>On Monday, I had a series of tweets (<a href="http://twitter.com/ddribin/status/9844373942">[1]</a>, <a href="http://twitter.com/ddribin/status/9845017202">[2]</a>, <a href="http://twitter.com/ddribin/status/9845380008">[3]</a>) about what I like about Java that I miss in Objective-C/Cocoa that were probably better off in a blog post. I blame <a href="http://twitter.com/jeff_lamarche">Jeff LaMarche</a> for <a href="http://twitter.com/ddribin/status/9843725157">baiting</a> me into the tweet rant, so here&#8217;s the the same thing, in blog post format with more detail and other points I forgot to mention.</p>

<h3>What I Miss</h3>

<p>Before settling in on Objective-C, I was a Java guy for about six years or so.  Overall, I much, <em>much</em> prefer coding in Objective-C to Java, and have no intentions of going back to Java.  But that doesn&#8217;t mean there&#8217;s some things I miss.  Here&#8217;s a quick list, with more detail below:</p>

<ul>
<li>A flexible I/O class hierarchy</li>
<li>Everything in <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html">java.util.concurrent</a></li>
<li>Exceptions for errors</li>
<li>Packages, a.k.a namespaces</li>
<li>One file for interface/implementation</li>
<li>Type safe enum classes</li>
<li>Annotations</li>
<li>Awesome IDEs (IntelliJ)</li>
</ul>
 <h3>A Flexible I/O Class Hierarchy</h3>

<p>Overall, I feel the <a href="http://java.sun.com/javase/6/docs/api/java/io/package-summary.html">java.io</a> package is really well designed.  I like the difference between <a href="http://java.sun.com/javase/6/docs/api/java/io/InputStream.html">InputStream</a>/<a href="http://java.sun.com/javase/6/docs/api/java/io/OutputStream.html">OutputStream</a> that are byte-oriented and <a href="http://java.sun.com/javase/6/docs/api/java/io/Reader.html">Reader</a>/<a href="http://java.sun.com/javase/6/docs/api/java/io/Writer.html">Writer</a> that are text-oriented. Also, there&#8217;s some cool subclasses such as <a href="http://java.sun.com/javase/6/docs/api/java/util/zip/GZIPInputStream.html">GZIPInputStream</a>, <a href="http://java.sun.com/javase/6/docs/api/java/util/zip/GZIPOutputStream.html">GZIPOutputStream</a>, and <a href="http://java.sun.com/javase/6/docs/api/java/io/LineNumberReader.html">LineNumberReader</a></p>

<p>Java&#8217;s InputStream and OutputStream are easier to subclass than <a href="http://developer.apple.com/Mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSInputStream_Class/Reference/Reference.html">NSInputStream</a> and <a href="http://developer.apple.com/Mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSOutputStream_Class/Reference/Reference.html">NSOutputStream</a> since there&#8217;s fewer methods to deal with.  Plus, there&#8217;s a lingering bug in NSInputStream that makes it effectively impossible to subclass in some really handy situations. See this <a href="http://lists.apple.com/archives/macnetworkprog/2007/May/msg00053.html">mailing list post from 2007</a> that mentions rdar://problem/322278.</p>

<h3>Everything in java.util.concurrent</h3>

<p>Ever since I read <a href="https://www.amazon.com/dp/0321349601?tag=davedribishom-20&amp;camp=0&amp;creative=0&amp;linkCode=as1&amp;creativeASIN=0321349601&amp;adid=0E62AD455C99P68HKK79&amp;">Java Concurrency in Practice</a>, I&#8217;ve been drooling over a lot of stuff Java programmers have available in their arsenal in <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html">java.util.concurrent</a>. The <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executor.html">Executor</a> is roughly equivalent to a <a href="http://developer.apple.com/mac/library/documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html">Grand Central Dispatch</a> queue and the<a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html">ExecutorService</a> is roughly equivalent to an <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/NSOperationQueue_class/Reference/Reference.html">NSOperationQueue</a>, but that&#8217;s where the similarities end. Granted, I think the Cocoa and GCD APIs are more palatable, especially since the introduction of <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html">blocks</a>, but there&#8217;s a bunch of classes we don&#8217;t have that would have been really useful at some point or another:</p>

<ul>
<li><a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html">BlockingQueue</a> and it&#8217;s implementations are handy for passing objects between threads. The need for this is partially mitigated by GCD, but it&#8217;d still be nice to have these to feed objects from one queue to another.</li>
<li><a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html">ConcurrentHashMap</a>is an awesome, thread safe and scalable map/dictionary.</li>
<li><a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html">CopyOnWriteArrayList</a> and <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArraySet.html">CopyOnWriteArraySet</a> are really nice for mostly read-only data.</li>
<li>The atomic classes in <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html">java.util.concurrent.atomic</a> are nicer than dealing with the <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/atomic.3.html#//apple_ref/doc/man/3/atomic">OSAtomic</a> functions.</li>
<li>The <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html">Future interface</a> has some very handy uses.  Mike Ash just wrote a blog post on <a href="http://mikeash.com/pyblog/friday-qa-2010-02-26-futures.html">futures in Objective-C</a>, but I think I prefer explicit futures to implicit futures.</li>
<li>The <a href="http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html">SwingWorker</a> class offers nice integration of asynchronous background tasks with the user interface thread.  I&#8217;ve used a similar pattern in Objective-C, but I think it&#8217;d be nice to have this encapsulated in a reusable object.</li>
<li>The <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/package-summary.html">java.util.concurrent.locks</a> package has some nice specialty locks such as <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html">ReentrantReadWriteLock</a>.</li>
</ul>

<h3>Exceptions for Errors</h3>

<p>Objective-C may have exceptions, but they are only used for programming errors or essentially fatal runtime errors. Error handling is done with <a href="http://developer.apple.com/mac/library/documentation/cocoa/conceptual/ErrorHandlingCocoa/ErrorHandling/ErrorHandling.html#//apple_ref/doc/uid/TP40001806-CH201-SW1">NSError</a>. This is different than Java, which uses exceptions for expected error cases, such as error reading from a file, or failure to execute a database transaction. This isn&#8217;t just a Java thing. Most modern languages like Python, Ruby, and C# use exceptions as Java does. Not using exceptions as error handling was one of the harder habits for me to break; however, I&#8217;ve come to embrace NSError and eschew exceptions in Objective-C, even if I don&#8217;t like it.</p>

<p>I&#8217;ve debated this a number of times with people, but having dealt with both exceptions and NSError, I still prefer exceptions. The big argument against exceptions is that they are non-local jumps causing confusing behavior and subtle bugs. I guess I&#8217;ve never seen this happen. Plus there&#8217;s also the fact that Foundation and AppKit are not exception safe, so throwing exceptions through these frameworks can and will lead to memory leaks and probably unpredictable behavior. Thus, the best course of action to handle an exception is to gracefully terminate the app.</p>

<p>To me, NSError doesn&#8217;t result in more robust code than exceptions. 90% of the time, people just pass NULL or log the NSError in place instead of passing it up to where it&#8217;s better handled. A big reason for this is that NSError is returned as an output parameter. Thus to pass an NSError up to a higher level requires  that an NSError be added to every method up the chain. Not only is this ungainly, but it&#8217;s sometimes not possible to add an NSError to an existing API. This is also a problem with checked exceptions Java, which is why most Java people endorse unchecked exceptions these days.</p>

<p>Exceptions really shine when you call multiple methods in a row that can fail.  In Objective-C, your best bet is to return early or use a goto. This still litters your code with error handling that drowns out the real code.  With exceptions, the error handling code is nicely separated from the &#8220;happy&#8221; code path.  Perhaps exceptions aren&#8217;t the be-all end-all of error handling, as I&#8217;ve recently been intrigued by the <a href="http://book.realworldhaskell.org/read/error-handling.html">error handling of Haskell</a>.  However, this is not something we&#8217;ll see in Objective-C any time soon.</p>

<h3>Packages, a.k.a Namespaces</h3>

<p>Classes in Objective-C live in a big, flat, global namespace. The common workaround is to prefix class names with two or three letters. Thus, I&#8217;d name my classes DDObject or some such. The problem with this approach is that two or three letters is just not enough of a namespace. It helps reduce collisions, but it does not eliminate them. Plus, Apple no longer uses only the NS prefix. It uses CA, CI, CV, QC, AB, UI, PS, IO, QL and probably more. A safe prefix today may be a collision tomorrow.</p>

<p>Things get even more dire when it comes to categories. Category smashing happens, and it&#8217;s <a href="http://blog.clickablebliss.com/2010/01/19/finding-colliding-category-methods/">hard to debug</a>. The only way to avoid it is to prefix your category methods with some unique prefix, as well.</p>

<p>Packages or namespace could theoretically solve both of these collisions.  This is not an unknown issue.  Many radars have been filed, such as <a href="http://openradar.appspot.com/7025435">rdar://problem/7025435</a>, that are all duped to a very low radar: rdar://problem/2821039. The problem is this isn&#8217;t an easy thing to bolt onto an existing language, because, of course, we want it done in a backwards compatible manner that doesn&#8217;t impact the performance of objc_msgSend(). So I understand why we don&#8217;t have it, but that doesn&#8217;t mean I don&#8217;t want it.</p>

<h3>One File for Interface and Implementation</h3>

<p>There are some good things about the separate of the interface in the .h file and the implementation in the .m file. However, I really despise having to keep these two up-to-date. Many accumulated hours have been lost to compile warnings and errors due to updating one without the other. The repeated method definitions are very <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">un-DRY</a>.</p>

<p>Others suggested that they like this separation of interface from implementation details, only exposing what&#8217;s necessary to users of the class, and conceptually I agree. In practice, I find it a chore. Perhaps the repeated code could be mitigated with some Xcode assistance. For example, add a method in the .m and it offers to add it to the .h for you. I think I could deal with this.</p>

<p>However, some of the private details are still exposed in the headers, namely the instance variables. The modern Objective-C runtime, available in 64-bit on Mac OS X and the native iPhone environments, allow synthesized ivars, meaning you can declare properties, and the ivars will automatically be created.  But you can&#8217;t really use this until you drop 32-bit Mac OS X and/or the simulator supports the modern runtime.</p>

<p>And even so, I&#8217;m not sold on synthesized ivars, as it requires using properties where I previously used ivars. To me, a property is conceptually different than an ivar, even if it&#8217;s non-public. Properties can be overridden, can have side effects, are available via key-value coding, and also have more overhead. Most of the time, I don&#8217;t want these things, and prefer direct ivar access.  I much prefer explicit ivars. Perhaps way to solve the exposed privates issue would be to declare them in the .m in say a class extension, instead of the .h. The runtime supports adding ivars at runtime, so this sounds technically possible.</p>

<h3>Type Safe Enum Classes</h3>

<p>Enums in Objective-C are inherited from C. Thus we get all the weaknesses of C enums for free. C enums are not much more than syntactic sugar for integer constants. There&#8217;s no way to get type safety, to introspect them, print them, loop over them, or do anything remotely fancy. The one benefit over a #define used to be that the debugger could decode the integer value into a readable name. But these days, all enums in Cocoa are anonymous, defined as such for 64-bit compatibility:</p>

<pre>enum {
    // Pass in one of the "By" options:
    NSStringEnumerationByLines = 0,
    // ...
};
typedef NSUInteger NSStringEnumerationOptions;
</pre>

<p>Thus most types that are enums are actually typedef&#8217;d to NSUInteger.  While this is necessary, it means we no longer get debugger integration with enum constants.</p>

<h3>Annotations</h3>

<p>Annotations in Java are bits of metadata that can be added to classes and methods.  Some of this metadata is used at compile time, but it is also available at runtime.  The runtime uses are intriguing, but one of the compile time annotations that I like is the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Override.html">@override annotation</a>.  This allows you to detect some subtle, yet easy-to-make mistakes when overriding methods in subclasses or a protocol:</p>

<ul>
<li>Accidentally overriding a superclass&#8217; method.</li>
<li>Misspelling a superclass&#8217; method, thus not actually overriding it.</li>
<li>Misspelling an optional protocol method, thus not actually implementing it.</li>
</ul>

<p>I&#8217;ve requested similar functionality for Objective-C in <a href="http://openradar.appspot.com/7215146"> rdar://problem/7215146</a>.</p>

<h3>Awesome IDEs (IntelliJ)</h3>

<p>This one has really nothing to do with the language.  Xcode has really improved over the years.  And while it is generally a very good text editor with project management, I&#8217;m afraid it still doesn&#8217;t compare to IntelliJ.  I don&#8217;t know how other Java IDEs stack up (I was never very impressed with Eclipse), but IntelliJ was the first IDE that sold me on the concept of IDEs (I used Emacs prior to it).</p>

<p>Honestly, this probably deserves a whole post in and of itself, but for starters, Xcode could really use intention actions, see <a href="http://openradar.appspot.com/7215136">rdar://problem/7215136</a>, and much better <a href="http://www.dribin.org/dave/blog/archives/2009/10/24/unit_test_bugs/">unit testing integration</a>.  IntelliJ has a bunch of other small niceties that all add up to a more pleasant development experience.  Unfortunately, it&#8217;s been years since I used IntelliJ, so I don&#8217;t remember all of the details.  Some I can remember are: real-time syntax checking, automatic import statement management, and customizable code reformatting (yes, I need to file bugs on these, too).</p>

<p>All I <em>do</em> remember as that it was the first and only development environment that really took much of the grunt work out of editing code.  It not only got out of my way, it actually made me more productive.  I dropped the $500 on it out of my own pocket, and it easily paid for itself (in real consulting dollars) in a matter of weeks.</p>
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2010-03-02T09:28:01-06:00</dc:date>
    </item>

    <item>
      <title>Mac and iPhone Applications with Unit Tests, Refactored</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/01/18/refactored_mac_iphone_app_with_tests/</link>
      <description>This is a follow-up to my post on why you should unit test Cocoa and iPhone applications. One reason I think Matt is against unit tests, at least given his particular examples, is that the tests themselves are quite large...</description>
      <guid isPermaLink="false">425@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>This is a follow-up to <a href="http://www.dribin.org/dave/blog/archives/2010/01/18/why_unit_test_cocoa_and_iphone/">my post</a> on why you should unit test Cocoa and iPhone applications.  One reason I think Matt is against unit tests, at least given his particular examples, is that the tests themselves are quite large and confusing.  They also use category smashing to override methods and inject mock objects and use runtime trickery to gain access to private instance variables.</p>

<p>These are all <a href="http://c2.com/xp/CodeSmell.html">code smells</a> that something isn&#8217;t right.  Remember, TDD is about tests <em>driving</em> development; however you must remember to <a href="http://www.google.com/search?rls=en&amp;q=tdd+listen+to+the+tests&amp;ie=UTF-8&amp;oe=UTF-8">listen to the tests</a> when they are crying out in pain.  I&#8217;m going to take Matt&#8217;s Mac and iPhone projects with unit tests and re-work them so that they are much more manageable and cleaner.</p>
 <h3>Duplicated Code</h3>

<p>This first smell I want to address is in the duplicated code between the Mac and iPhone applications.  Both apps have a <code>CLLoationManager</code> delegate that listens for updates and formats the location into HTML for the web view, strings labels for the buttons, and a Google Maps URL.  The code between these two apps is identical and is a good example of a violation of the Don&#8217;t Repeat Yourself, or <a href="http://c2.com/cgi/wiki?DontRepeatYourself">DRY</a>, Principle.</p>

<p>So how do we remove this duplicated code?  Part of what makes this difficult is that it is highly <a href="http://c2.com/cgi/wiki?CouplingAndCohesion">coupled</a> to the UI.  In the Mac app, this code lives in an <code>NSWindowController</code> subclass, and in the iPhone app it lives in a <code>UIViewController</code> subclass.  Thus we can&#8217;t just share an existing class as-is between projects because you can&#8217;t use an <code>NSWindowController</code> in an iPhone app and you can&#8217;t use a <code>UIViewController</code> in a Mac app.  The answer is to <a href="http://www.refactoring.com/catalog/extractClass.html">extract this code into a new class</a> that can be used from both applications.</p>

<p>Because the primary function of this new class is to take core location updates and format them to various strings, I&#8217;m calling the class <code>MyCoreLocationFormatter</code>.  There may be a better name, since using the word formatter may imply an <code>NSFormatter</code> subclass, but let&#8217;s stick with it for now.</p>

<p>The sticking point is that we somehow need this new class to update the UI, irrespective of Cocoa vs. Cocoa Touch.  We need to break the direct dependency on Cocoa and Cocoa Touch, and I&#8217;ve chosen to use a delegate with a single method as a bit of <a href="http://www.objectmentor.com/resources/articles/dip.pdf">dependency inversion</a>:</p>

<pre>
@protocol MyCoreLocationFormatterDelegate &lt;NSObject&gt;

- (void)locationFormatter:(MyCoreLocationFormatter *)formatter
 didUpdateFormattedString:(NSString *)formattedString
            locationLabel:(NSString *)locationLabel
           accuractyLabel:(NSString *)accuracyLabel;

@end
</pre>

<p>Thus, when the location changes, it formats the new location into appropriate strings and sends this message to its delegate.  Both <code>WhereIsMyMacWindowController</code> and <code>WhereIsMyPhoneViewController</code> implement this protocol, and when they receive the message, the update their UI accordingly.</p>

<p>There are other ways to achieve similar decoupling.  We could use an <code>NSNotification</code> to send out the update with the strings in the user info dictionary.  Or we could have properties for the three strings and allow interested parties to monitor their updates using <a href="http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html">key-value observing</a>.  On the Mac side, this enables you to use <a href="http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/CocoaBindings/CocoaBindings.html">Cocoa bindings</a> to wire up the UI.  Or we could return a dictionary with the three strings.  Or we could create a new <a href="http://c2.com/cgi/wiki?ValueObject">value object</a> and return that.  Any of these alternatives are viable, however I think using a delegate makes the coupling a bit more explicit and easier to follow.  What&#8217;s important is that the direct dependency to the UI layer is broken.</p>

<p>Here&#8217;s the full interface of <code>MyCoreLocationFormatter</code>:</p>

<pre>
@interface MyCoreLocationFormatter : NSObject &lt;CLLocationManagerDelegate&gt;
{
    id&lt;MyCoreLocationFormatterDelegate&gt; _delegate;
    NSString * _formatString;
}

@property (nonatomic, assign, readwrite) id&lt;MyCoreLocationFormatterDelegate&gt; delegate;
@property (nonatomic, copy, readonly) NSString * formatString;

- (id)initWithDelegate:(id&lt;MyCoreLocationFormatterDelegate&gt;)delegate
          formatString:(NSString *)htmlFormatString;

- (NSURL *)googleMapsUrlForLocation:(CLLocation *)currentLocation;

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation;

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error;

@end
</pre>

<p>Ignoring the <code>CLLocationManager</code> delegate methods, there are only two methods. The format string is used as the HTML template that gets loaded from the application&#8217;s bundle.  The <code>-googleMapsUrlForLocation:</code> method is used to open the location up in a browser.</p>

<p>To test this class, we use a mock object to ensure the delegate is being called properly.  We use instance variables and our fixture methods to setup an instance of <code>MyCoreLocationFormatter</code> and the mock delegate:</p>

<pre>
- (void)setUp
{
    // Setup
    _mockDelegate = [OCMockObject mockForProtocol:@protocol(MyCoreLocationFormatterDelegate)];
    _formatter = [[MyCoreLocationFormatter alloc] initWithDelegate:_mockDelegate
                                                    formatString:@"ll=%f,%f spn=%f,%f"];
}

- (void)tearDown
{
    // Verify
    [_mockDelegate verify];

    // Teardown
    [_formatter release]; _formatter = nil;
}
</pre>

<p>With these fixtures in place, writing our tests are fairly straight forward:</p>

<pre>
- (void)testUpdateToNewLocationSendsUpdateToDelegate
{
    // Setup
    CLLocation * location = [self makeLocationWithLatitude:-37.80996889 longitude:144.96326388];
    [[_mockDelegate expect] locationFormatter:_formatter
                     didUpdateFormattedString:@"ll=-37.809969,144.963264 spn=-0.000018,-0.000014"
                                locationLabel:@"-37.809969, 144.963264"
                               accuractyLabel:[NSString stringWithFormat:@"%f", kCLLocationAccuracyBest]];

    // Execute
    [_formatter locationManager:nil didUpdateToLocation:location fromLocation:nil];
}

- (void)testUpdateToSameLocationDoesNotSendUpdateToDelegate
{
    // Setup
    CLLocation * location = [self makeLocationWithLatitude:-37.80996889 longitude:144.96326388];

    // Execute
    [_formatter locationManager:nil didUpdateToLocation:location fromLocation:location];
}

- (void)testFailedUpdateSendsUpdateToDelegate
{
    // Setup
    NSError * error = [self makeFakeErrorWithDescription:@"Some error description"];
    [[_mockDelegate expect] locationFormatter:_formatter
                     didUpdateFormattedString:@"Location manager failed with error: Some error description"
                                locationLabel:@""
                               accuractyLabel:@""];


    // Execute
    [_formatter locationManager:nil didFailWithError:error];
}
</pre>

<p>In order to keep the tests short and concise, I&#8217;ve moved the lengthy code to create a <code>CLLocation</code> and an <code>NSError</code> out of the tests and into helper methods.  Remember, you&#8217;ve got to keep test code clean and maintainable, too.  All three of these tests are only about 35 lines of code.</p>

<p>In contrast, Matt&#8217;s two original test methods were over 200 lines of code.  The problem is that Matt&#8217;s code is testing the string formatting by asserting the web view&#8217;s HTML and text field&#8217;s strings.  Separating the responsibility of formatting the strings from updating the UI not only improves the design, but makes testing much simpler.</p>

<p>So we&#8217;ve got on almost order of magnitude less code in our test methods that&#8217;s cleaner with the same code coverage.  As a bonus, this class can be used in both the Mac and iPhone applications, so we can re-use the core logic.  From an <a href="http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html">MVC</a> perspective, the new <code>MyCoreLocationFormatter</code> class would be considered the model that is used with different views.  Pushing logic out of the controller layer and into a model pays homage to the <a href="http://www.google.com/search?rls=en&amp;q=skinny+controller,+fat+model&amp;ie=UTF-8&amp;oe=UTF-8">skinny controller, fat model</a> design guideline.</p>

<h3>Removing Testing Hacks</h3>

<p>With this class complete, we can now move on to testing the <code>WhereIsMyMacWindowController</code> class.  Matt&#8217;s test code uses a couple of hacks in order to enable testing that I consider code smells.</p>

<p>First, it uses runtime trickery, namely <code>object_getInstanceVariable</code> and <code>object_setInstanceVariable</code>, to gain access to the outlet instance variables.  I think this is bad form and prefer to add public accessors for the outlets using properties:</p>

<pre>
@property (assign) IBOutlet WebView *webView;
@property (assign) IBOutlet NSTextField *locationLabel;
@property (assign) IBOutlet NSTextField *accuracyLabel;
@property (assign) IBOutlet NSButton *openInBrowserButton;
</pre>

<p>Using <code>IBOutlet</code> on a property means the NIB loading code will go through this public interface as well.  Since these properties are already settable by the NIB loading code, I don&#8217;t see a big downside to making them public.</p>

<p>Second, the tests use category smashing to inject mock objects of <code>CLLocationManager</code> and <code>NSWorkspace</code> for testing.  Again, I think this is bad form and prefer explicit <a href="http://martinfowler.com/articles/injection.html">dependency injection</a> as a cleaner way to do this.  I&#8217;m going to use constructor injection by adding these two initializers to <code>WhereIsMyMacWindowController</code>:</p>

<pre>
- (id)init;

// Designated Initializer
- (id)initWithLocationManager:(CLLocationManager *)locationManager
            locationFormatter:(MyCoreLocationFormatter *)locationFormatter
                    workspace:(NSWorkspace *)workspace;
</pre>

<p>The no-argument initializer calls the designated initializer with a new location manager, new location formatter, and the shared workspace.  This allows production code to use the no-argument initializer and allows test code to use the designated initializer in order to inject <a href="http://xunitpatterns.com/Test%20Double.html">test doubles</a>, such as mock objects.</p>

<p>Some may find it odd to pass in an instance of <code>NSWorkspace</code>.  I agree, it is a bit odd, but it&#8217;s necessary because it&#8217;s a singleton and hard to stub out for testing.  There are other ways to achieve this, such as the category smashing Matt uses, or using a custom factory class that can be overridden by unit tests.  However, eliminating the use of a singleton in the logic and using dependency injection is far more flexible.  What if, for example, we wanted to run tests concurrently, like <a href="http://github.com/gabriel/gh-unit">GHUnit</a> allows?  Now we&#8217;ve got to deal with thread safety issues when overriding the  shared global instance. Remember, a singleton is a global in sheep&#8217;s clothing.</p>

<p>With these two hacks addressed, our tests in <code>WhereIsMyMacWindowControllerTests</code> become simpler.  Again, I update the fixture to create mock objects for the various dependencies:</p>

<pre>
- (void)setUp
{
    // Setup
    _mockLocationManager = [OCMockObject mockForClass:[CLLocationManager class]];
    _mockLocationFormatter = [OCMockObject mockForClass:[MyCoreLocationFormatter class]];
    _mockWorkspace = [OCMockObject mockForClass:[NSWorkspace class]];
    _windowController = [[WhereIsMyMacWindowController alloc]
                         initWithLocationManager:_mockLocationManager
                         locationFormatter:_mockLocationFormatter
                         workspace:_mockWorkspace];
}

- (void)tearDown
{
    // Verify
    [_mockLocationManager verify];
    [_mockLocationFormatter verify];
    [_mockWorkspace verify];

    // Teardown
    [_windowController release]; _windowController = nil;
}
</pre>

<p>Here&#8217;s a few of the tests to show what a big difference these changes make:</p>

<pre>
- (void)testWindowDidLoadStartsLocationManager
{
    // Setup
    [[_mockLocationManager expect] setDelegate:_mockLocationFormatter];
    [[_mockLocationManager expect] startUpdatingLocation];

    // Execute
    [_windowController windowDidLoad];
}

- (void)testOpenInDefaultBrowserActionOpensGoogleMapsUrlInWorkspace
{
    // Setup
    [[[_mockLocationManager stub] andReturn:nil] location];
    NSURL * dummyUrl = [NSURL URLWithString:@"http://example.com/"];
    [[[_mockLocationFormatter stub] andReturn:dummyUrl] googleMapsUrlForLocation:nil];
    [[_mockWorkspace expect] openURL:dummyUrl];

    // Execute
    [_windowController openInDefaultBrowser:nil];
}

- (void)testCloseStopsLocationManager
{
    // Setup
    [[_mockLocationManager expect] stopUpdatingLocation];

    // Execute
    [_windowController close];
}
</pre>

<p>Note that I also moved the call to <code>-stopUpdatingLocation</code> from <code>-dealloc</code> to <code>-close</code>.  I try to use <code>-dealloc</code> only for cleaning up memory related resources, which is especially important in a garbage collected environment.  This also means we don&#8217;t have to stub out the call to <code>-stopUpdatingLocation</code> everywhere, making our tests simpler, too.</p>

<p>The test to ensure that the location formatter delegate updates the web view and test fields is still a bit lengthy:</p>

<pre>
- (void)testLocationFormatterDelegateUpdatesUI
{
    // Setup
    id mockWebView = [OCMockObject mockForClass:[WebView class]];
    id mockWebFrame = [OCMockObject mockForClass:[WebFrame class]];
    id mockLocationLabel = [OCMockObject mockForClass:[NSTextField class]];
    id mockAccuracyLabel = [OCMockObject mockForClass:[NSTextField class]];

    _windowController.webView = mockWebView;
    _windowController.locationLabel = mockLocationLabel;
    _windowController.accuracyLabel = mockAccuracyLabel;

    [[[mockWebView stub] andReturn:mockWebFrame] mainFrame];
    [[mockWebFrame expect] loadHTMLString:@"html string" baseURL:nil];
    [[mockLocationLabel expect] setStringValue:@"location"];
    [[mockAccuracyLabel expect] setStringValue:@"accuracy"];

    // Execute
    [_windowController locationFormatter:_mockLocationFormatter
                didUpdateFormattedString:@"html string"
                           locationLabel:@"location"
                           accuracyLabel:@"accuracy"];

    // Verify
    [mockWebFrame verify];
    [mockLocationLabel verify];
    [mockAccuracyLabel verify];
}
</pre>

<p>Personally, I&#8217;m not a big fan of these kinds tests, as well as tests that ensure outlets are setup properly after the NIB loads.  If you stick with the skinny controller, fat model principle, the controllers become so simple they&#8217;re almost not worth testing.  Just as you don&#8217;t test simple accessors because there&#8217;s little benefit to doing so, I don&#8217;t know that it&#8217;s necessarily worth it to get 100% code coverage on your controller classes.  You still get a big benefit if the bulk of your code is in testable model classes, so this isn&#8217;t much of a loss.</p>

<p>There&#8217;s more changes I&#8217;ve made to the Mac application, and I&#8217;ve given the same treatment to the iPhone application, but I don&#8217;t want to make this post any longer than it already is.  <a href="https://bitbucket.org/ddribin/whereismyx/src/">View</a> the code I put up on Bitbucket, or <a href="https://bitbucket.org/ddribin/whereismyx/get/2010-01-18.tar.bz2">download a tarball</a>, to see the final result.</p>
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2010-01-18T20:40:37-06:00</dc:date>
    </item>

    <item>
      <title>Why Unit Test Cocoa and iPhone Applications</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/01/18/why_unit_test_cocoa_and_iphone/</link>
      <description>Matt Gallagher, on his absolutely fantastic Cocoa with Love blog, recently wrote a series of posts about test driven development (TDD) and unit testing Mac and iPhone applications: A sample Mac application with complete unit tests A sample iPhone application...</description>
      <guid isPermaLink="false">424@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>Matt Gallagher, on his absolutely fantastic <a href="http://cocoawithlove.com/">Cocoa with Love</a> blog, recently wrote a series of posts about test driven development (TDD) and unit testing Mac and iPhone applications:</p>

<ul>
<li><a href="http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html">A sample Mac application with complete unit tests</a></li>
<li><a href="http://cocoawithlove.com/2009/12/sample-iphone-application-with-complete.html">A sample iPhone application with complete unit tests</a></li>
<li><a href="http://cocoawithlove.com/2010/01/high-quality-in-software-development.html">Quality control in application development without unit testing</a></li>
</ul>

<p>However, I heartily disagree with a major point in the conclusion of his final post:</p>

<blockquote>
  <p>Unit testing an application is filled with difficulties and problems. In my development style, I consider the time cost of unit testing an application outweighs its benefits — especially since a unit tested application still requires system tests like user-interface and regression tests for proper validation.</p>
</blockquote>

<p>Before I talk about why I disagree, I want to say that I <em>do</em> agree with the next part of the conclusion:</p>

<blockquote>
  <p>Regardless of whether you use unit tests, formalized system testing — either automated or manual and methodical — is required to fully validate an application and ensure the lowest possible low bug rates.</p>
</blockquote>
 <p>Unit testing, while practicing TDD, is <a href="http://www.makinggoodsoftware.com/2009/11/21/tdd-is-not-about-testing/">not about testing</a>, in the traditional sense.  Unit testing does <em>not</em> tell you that your final application is actually easy to use by the end user.  Unit testing does <em>not</em> tell you that you actually built an application that solves the problems you intended to address.  Unit testing does <em>not</em> tell you if all your units work together once wired up.  That&#8217;s what higher level acceptance and system tests are for.  Acceptance and system tests are required to ensure the overall quality of your application.</p>

<p>However, this doesn&#8217;t make unit testing worthless.  Applications have two kinds of quality:  <a href="http://c2.com/cgi/wiki?InternalAndExternalQuality">external and internal</a>.  <em>External quality</em> is how the end users perceive the quality of the application: does it crash, is it easy to use, etc.  Acceptance and system tests keep the external quality high.  <em>Internal quality</em> is how the developers perceive the quality of the code: is easy to understand and maintain, etc.  TDD and unit tests are about keeping the internal quality of the application high.  High internal quality makes bugs easier to find and features easier to implement.  Unit tests provide an essential safety net to be able to refactor your code, improve the design, and avoid <a href="http://en.wikipedia.org/wiki/Software_rot">code rot</a>.  Ultimately this makes software cheaper (and more fun!) to write and easier to stay on schedule.</p>

<p>Thus any real world application should have both unit tests <em>and</em> acceptance tests.  They are not mutually exclusive and they do not serve the same purpose.  I honestly believe that if writing unit tests for TDD is slowing you down, then you are not properly practicing TDD.  Remember TDD is a learned skill, and like any learned skill, it&#8217;s not something you pick up overnight.  It takes practice.  Is TDD a panacea? No, it&#8217;s not going to cure cancer and bring world peace, but I think <a href="http://blog.objectmentor.com/articles/2009/10/08/tdd-triage">it is the best tool we currently have</a> in our arsenal to keep code clean, flexible, and maintainable.</p>
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2010-01-18T12:33:45-06:00</dc:date>
    </item>

    <item>
      <title>Handy sudo Settings</title>
      <link>http://www.dribin.org/dave/blog/archives/2010/01/13/handy_sudo_settings/</link>
      <description>By and large, sudo on Mac OS X comes setup with some sane defaults. But here&#8217;s two lines I add to my /etc/sudoers file on a fresh install: Defaults passprompt=&quot;%u@%h&apos;s password: &quot; Defaults timestamp_timeout=15 The first line changes the password...</description>
      <guid isPermaLink="false">423@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>By and large, <a href="http://www.gratisoft.us/sudo/"><code>sudo</code></a> on Mac OS X comes setup with some sane defaults.  But here&#8217;s two lines I add to my <a href="http://www.gratisoft.us/sudo/man/sudoers.html"><code>/etc/sudoers</code></a> file on a fresh install:</p>

<pre><code>Defaults        passprompt="%u@%h's password: "
Defaults        timestamp_timeout=15
</code></pre>

<p>The first line changes the password from something generic:</p>

<pre><code>% sudo whoami
Password:
root
</code></pre>

<p>To something a lot more useful:</p>

<pre><code>% sudo whoami
dave@fuji's password: 
root
</code></pre>

<p>The second line changes the time between needing to re-enter your password from 5 minutes to 15 minutes.  This is handy if you&#8217;re confident you&#8217;re in a fairly secure physical environment, like an iMac at home, and you find <code>sudo</code> asking for your password too frequently.  If you work in a more paranoid physical environment, you may want to keep the timeout at 5 minutes.</p>

<p>Remember to edit the file with <a href="http://www.gratisoft.us/sudo/man/visudo.html"><code>visudo(8)</code></a>.  Don&#8217;t edit it directly.</p>

<pre><code>% sudo EDITOR=emacs visudo
</code></pre>
 
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2010-01-13T22:33:08-06:00</dc:date>
    </item>

    <item>
      <title>My First NES Homebrew</title>
      <link>http://www.dribin.org/dave/blog/archives/2009/12/20/first_nes_homebrew/</link>
      <description>One of my gifts to my wife, Nancy, for her birthday this year was the Happy Birthday song, chiptune style. It&#8217;s an actual NES program, hand-coded in 6502 assembly. This is the first original NES program I&#8217;ve written, and could...</description>
      <guid isPermaLink="false">422@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>One of my gifts to my wife, Nancy, for her birthday this year was the Happy Birthday song, <a href="http://en.wikipedia.org/wiki/Chiptune">chiptune style</a>.  It&#8217;s an actual <a href="http://en.wikipedia.org/wiki/Nintendo_Entertainment_System">NES</a> program, hand-coded in <a href="http://en.wikipedia.org/wiki/6502">6502</a> assembly.  This is the first original NES program I&#8217;ve written, and could be considered my first <a href="http://en.wikipedia.org/wiki/Homebrew_(video_games)">homebrew</a> or even <a href="http://en.wikipedia.org/wiki/Demo_(computer_programming)">demo</a>.  While you can download the <a href="http://www.dribin.org/dave/resources/files/2009/nancy_birthday.nes">ROM</a> and run it yourself, here&#8217;s a video of it running in <a href="http://www.bannister.org/software/nestopia.htm">Nestopia</a>, an NES emulator [<a href="http://www.youtube.com/watch?v=RzIUPaIICqA">YouTube link</a>]:</p>

<p><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/RzIUPaIICqA&amp;hl=en_US&amp;fs=1&amp;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/RzIUPaIICqA&amp;hl=en_US&amp;fs=1&amp;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>

<p>Some interesting stats about this program:</p>
 <ul>
<li>The song data is 485 bytes for 42 seconds of music.</li>
<li>The assembled code is 575 bytes.</li>
<li>It uses 32 bytes of RAM at runtime, not including stack.</li>
<li>It uses probably 10 bytes of stack.</li>
<li>The graphics are 8 kilobytes.</li>
<li>The ROM file is 24 kilobytes (mostly zeroes, though).</li>
<li>The video file I uploaded to YouTube was 784 kilobytes.</li>
</ul>

<p>Much thanks to BunnyBoy and MetalSlime for their <a href="http://www.nintendoage.com/faq/nerdy_nights_out.html">&#8220;Nerdy Nights&#8221;</a> NES coding tutorials on <a href="http://www.nintendoage.com/">Nintedo Age</a>.  The NES sound engine is all MetalSlime&#8217;s genius. I just plugged in the notes. The music itself was adapted from some <a href="http://www.virtualsheetmusic.com/downloads/Miscellaneous/HappyBirth.html">sheet music</a> I found.  The lame &#8220;graphics&#8221; are all mine. I don&#8217;t know how to do much other than scroll the background and change the color palette, at the moment.</p>

<p>Also, the <a href="http://nesdev.parodius.com/">NesDev</a> archive and wiki were invaluable as a technical references.  For the toolchain, I used <a href="http://www.cc65.org/">cc65</a>, which includes a very nice assembler and linker for 6502.  It would be nice to run this on actual hardware at some point using flash cartridge like the <a href="http://www.retrousb.com/product_info.php?cPath=24&amp;products_id=34">PowerPak</a>.</p>

<p>I started learning NES programming only a few months ago.  It&#8217;s just one of those useless skills I&#8217;ve wanted to learn for a while now.  I probably had a bit of head start since I learned 6502 assembly back in the day on an <a href="http://en.wikipedia.org/wiki/Apple_II_series">Apple ][</a>.  Granted, that was a long time ago, but it&#8217;s a very simple CPU architecture so it comes back pretty fast.</p>
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2009-12-20T13:40:23-06:00</dc:date>
    </item>

    <item>
      <title>Mercurial and HTTP Passwords</title>
      <link>http://www.dribin.org/dave/blog/archives/2009/12/20/mercurial_http_passwords/</link>
      <description>Authenticated Mercurial repositories are generally handled in one of two ways: HTTP authentication or SSH. Prior to Mercurial version 1.3, the best way to handle authenticated repositories so that you didn&#8217;t have to enter your password on every transaction was...</description>
      <guid isPermaLink="false">421@http://www.dribin.org/dave/blog/</guid>
      <content:encoded>
        <![CDATA[<p>Authenticated <a href="http://mercurial.selenic.com/">Mercurial</a> repositories are generally handled in one of two ways: HTTP authentication or SSH.  Prior to Mercurial version 1.3, the best way to handle authenticated repositories so that you didn&#8217;t have to enter your password on every transaction was to use SSH with ssh-agent, or, if you were running Mac OS X, use Jonathan Wight&#8217;s <a href="http://bitbucket.org/schwa/hgkeychain/">hgkeychain</a> extension, which stored HTTP passwords in the Mac OS X keychain.  As of Mercurial 1.3, there&#8217;s a new way to handle authenticated HTTP repositories that I&#8217;ve just started using.</p>
 <p>Mercurial 1.3 added official support was for storing HTTP authentication information in <code>.hg/hgrc</code>.  The official documentation for this is in the <a href="http://www.selenic.com/mercurial/hgrc.5.html#auth">hgrc.5</a> man page, but there&#8217;s also a <a href="http://hgtip.com/tips/advanced/2009-10-01-configuring-user-auth-https/">good article on hgtip.com</a> on how to set it up.  The gist of it is you put something like this in your <code>.hg/hgrc</code>:</p>

<pre><code>[auth]
bb.prefix = https://bitbucket.org
bb.username = {username}
bb.password = {password}
</code></pre>

<p>The problem with this solution is that your password is stored as plaintext.  Enter <a href="http://pypi.python.org/pypi/mercurial_keyring"><code>mercurial_keyring</code></a>, also known as the <a href="http://mercurial.selenic.com/wiki/KeyringExtension">keyring extension</a>.  If you leave the password out of your <code>hgrc</code>, the keyring extension will prompt you for the password and store it in a system specific password database, such as the OS X keychain, Gnome Keyring, or KDE KWallet.</p>

<p>Earlier versions had one drawback: it stored passwords indexed on the repository&#8217;s URL.  For example, if you had two repositories on BitBucket, you&#8217;d have to enter your password twice, once for each repository.  This wasn&#8217;t ideal, especially when you have many repositories on BitBucket.  Once I entered my BitBucket password, I shouldn&#8217;t have to enter it again.</p>

<p>So I forked the project and and modified it so that saved passwords are indexed on the URL prefix you setup in <code>hgrc</code>.  Thus, all authenticated BitBucket repositories will share the same password.  My patches were accepted and included in version 0.4.0 of <a href="http://pypi.python.org/pypi/mercurial_keyring"><code>mercurial_keychain</code></a>.  I&#8217;ve only been using it for a day now, but it&#8217;s been working out well so far.</p>
]]>
      </content:encoded>
      <dc:subject>Tech</dc:subject>
      <dc:date>2009-12-20T10:44:09-06:00</dc:date>
    </item>


  </channel>
</rss>


