<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Red Sweater Blog &#187; Xcode</title>
	<atom:link href="http://www.red-sweater.com/blog/category/articles/xcode/feed" rel="self" type="application/rss+xml" />
	<link>http://www.red-sweater.com/blog</link>
	<description>Mac &#38; Technology Writings by Daniel Jalkut</description>
	<lastBuildDate>Tue, 17 Jan 2012 22:03:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.1</generator>
		<item>
		<title>The Power Of Plist</title>
		<link>http://www.red-sweater.com/blog/2083/the-power-of-plist</link>
		<comments>http://www.red-sweater.com/blog/2083/the-power-of-plist#comments</comments>
		<pubDate>Wed, 03 Aug 2011 19:12:50 +0000</pubDate>
		<dc:creator>Daniel Jalkut</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Darwin]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://www.red-sweater.com/blog/?p=2083</guid>
		<description><![CDATA[Most Mac and iOS developers know that when you build an application, you advertise a number of details about the application in the &#8220;Info.plist&#8221; file, located inside the application bundle. You can examine any application on your Mac and see what kind of information the developer has conveyed about it: Navigate to a .app file [...]]]></description>
			<content:encoded><![CDATA[<p>Most Mac and iOS developers know that when you build an application, you advertise a number of details about the application in the &#8220;Info.plist&#8221; file, located inside the application bundle. You can examine any application on your Mac and see what kind of information the developer has conveyed about it:</p>
<ol>
<li>Navigate to a .app file in the Finder, e.g. /Applications/Mail.app</li>
<li>Control-click the app icon and select &#8220;Show Package Contents&#8221;</li>
<li>Navigate to Contents/Info.plist</li>
<li>Open with a plist editor or your favorite text editor.</li>
</ol>
<p>These files advertise a number of interesting attributes including the application&#8217;s official version and copyright strings. They also include important clues to the system about what kinds of files the application knows how to read and write, and what its minimum system requirements are.</p>
<h3>Minimum System Requirements</h3>
<p>Declaring the right Info.plist values not only allows a developer to control which operating systems a product should run on, but which of the application&#8217;s architectures should be considered for a particular operating system. For example, <a href="http://www.red-sweater.com/blackink/">Black Ink</a> uses a number of keyed values describing its requirements:</p>
<pre>	&lt;key&gt;LSArchitecturePriority&lt;/key&gt;
	&lt;array&gt;
		&lt;string&gt;x86_64&lt;/string&gt;
		&lt;string&gt;i386&lt;/string&gt;
		&lt;string&gt;ppc&lt;/string&gt;
	&lt;/array&gt;
	&lt;key&gt;LSMinimumSystemVersion&lt;/key&gt;
	&lt;string&gt;10.4.0&lt;/string&gt;
	&lt;key&gt;LSMinimumSystemVersionByArchitecture&lt;/key&gt;
	&lt;dict&gt;
		&lt;key&gt;i386&lt;/key&gt;
		&lt;string&gt;10.4.0&lt;/string&gt;
		&lt;key&gt;x86_64&lt;/key&gt;
		&lt;string&gt;10.6.0&lt;/string&gt;
		&lt;key&gt;ppc&lt;/key&gt;
		&lt;string&gt;10.4.0&lt;/string&gt;
	&lt;/dict&gt;
</pre>
<p>Notice the fidelity of some of these options. Black Ink is an application that is compiled with binary code for three separate architectures embedded into it: 64-bit Intel, 32-bit Intel, and 32-bit PowerPC. In order to give the user the best possible experience after they double-click the application icon, the system consults the Info.plist values to determine which binary is most appropriate to load on the current system.</p>
<p>The options for Black Ink start by indicating that all things being equal, it prefers to run as 64-bit Intel, but will settle for 32-bit Intel or PowerPC in a pinch. Next, it conveys that it should not be run on any operating system earlier than Mac OS X 10.4. Finally, it adds an additional restriction by architecture, stating that in the case of 64-bit Intel, the system should consider Mac OS X 10.6 the minimum required OS.</p>
<p>Why so picky? For example, Mac OS X 10.5 will run on computers that are new enough to support 64-bit Intel code, but the 10.5 operating environment itself doesn&#8217;t contain enough compatible libraries to make it very useful to a full-featured Cocoa application. So we need to convince the 10.5 system <em>to ignore our 64-bit Intel code.</em> And this is how it&#8217;s done.</p>
<h3>Embedding Info.plist</h3>
<p>This is all well and good for applications, but what about other code that may be run on a variety of hardware and operating systems? In particular, command-line tools do not come in the same bundled-folder format that applications do. Fortunately, Apple thought of this when they implemented support in their developer tools for embedding the contents of an Info.plist directly into the binary itself. You just have to pass the Info.plist path to Apple&#8217;s linker tool when it&#8217;s constructing your binary file. (Thanks to <a href="http://www.noodlesoft.com/">Paul Kim</a> for reminding me of this functionality). What this means in practice is adding arguments like this to your Xcode target&#8217;s &#8220;Other Linker Flags&#8221; build setting:</p>
<pre>-sectcreate __TEXT __info_plist $(INFOPLIST_FILE)
</pre>
<p>This instructs the linker to crete a new text segment named &#8220;__info_plist&#8221; in the resulting binary, and to fill it with the contents of the referenced Info.plist file. To make sure the INFOPLIST_FILE expands correctly, just make sure you set it in the separate build setting for identifying the Info.plist (the one you&#8217;d normally use in an app, and that is just ignored by default for a command-line tool target).</p>
<p>I brushed up on all this information because I wanted to help ensure that some recent work I did to create a <a href="https://github.com/danielpunkass/peg-multimarkdown">standalone MultiMarkdown tool</a> would be backward compatible with older systems. This required <a href="https://github.com/danielpunkass/peg-multimarkdown/commit/ca523bac1fb03b9cfdcf540805e677086c063704">adding an embedded plist</a> much as I&#8217;m describing here.</p>
<p>(<strong>Note:</strong> I have gotten some feedback to the effect that the __info_plist segment&#8217;s minimum system version requirements may not actually be consulted properly on Mac OS X 10.5. This would be a bummer, and in fact sort of reject the whole point of embedding the Info.plist in this case. I&#8217;m going to see if I can confirm whether it doesn&#8217;t in fact work.)</p>
<p>You could technically embed all kinds of stuff in the binary, with different section names. But the contract in this case is that when Mac OS X is determining information about an executable, it will consult <strong>the bundle&#8217;s Info.plist file</strong>, if it happens to be an executable in a bundle, or <em>the binary&#8217;s __info_plist segment</em>, if it happens to have one.</p>
<p>Another common reason for needing to embed Info.plist information into a standalone binary is if you are using Apple&#8217;s code signing mechanism to sign an individual binary tool. Code signing uses information from the Info.plist of a product, and in the case of standalone binaries, the only product-cohesive place to put this is in the binary itself.</p>
<h3>Examining Binary Info.plists</h3>
<p>After you&#8217;ve performed the magic above, you&#8217;ll probably be keen to inspect your command-line tool&#8217;s Info.plist to see if it worked. To do this, you can use the otool command from the Finder. If you run otool with the &#8220;-l&#8221; option to show all load commands, it will include the load command that identifies the __info_plist segment. Use grep to narrow it down to the part you&#8217;re interested in:</p>
<pre>otool -l ./yourTool | grep info_plist -B1 -A10
</pre>
<p>Any results at will confirm that there is Info.plist information in the binary, but how does it look? The &#8220;-s&#8221; option to otool lets you examine the contents of a specific segment in a binary, but it dumps it out as hex code. Fortunately, another system-bundled tool called &#8220;xxd&#8221; is capable of easily converting between hex-dump and text formats. As it turns out, some of Apple&#8217;s bundled developer tools (at least on my Mac) contain these embedded __info_plist sections, so if you don&#8217;t have a command line tool of your own to try this on, you can peek at what the &#8220;atos&#8221; tool has to say for itself:</p>
<pre>otool -s __TEXT __info_plist /usr/bin/atos | xxd -r
</pre>
<h3>In Summary</h3>
<p>Info.plist values are important for conveying information about your product, from the crudest, most obvious stuff like version number, to the most nuanced details such as which architectures are supported. Knowing how to specify an application or tool&#8217;s requirements as precisely as possible will ensure that the product performs optimally on whatever supported system your user happens to be using. I&#8217;ve barely scratched the surface here with a few common deployment keys that control execution behavior on Mac OS X. Be sure to skim Apple&#8217;s <a href="http://developer.apple.com/library/mac/#documentation/General/Reference/InfoPlistKeyReference/Introduction/Introduction.html">Information Property List Key Reference</a> to see if there are other useful bits of information you can share for your application <em>or for your command-line tool.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.red-sweater.com/blog/2083/the-power-of-plist/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>RegExKitLite v. Clang</title>
		<link>http://www.red-sweater.com/blog/1345/regexkit-clang</link>
		<comments>http://www.red-sweater.com/blog/1345/regexkit-clang#comments</comments>
		<pubDate>Fri, 23 Jul 2010 21:42:21 +0000</pubDate>
		<dc:creator>Daniel Jalkut</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://www.red-sweater.com/blog/?p=1345</guid>
		<description><![CDATA[I finally updated to Xcode 3.2.3. I was a little late because I had other priorities, but I wanted to get my iPhone projects building and installing onto my iPhone OS 4.0 devices, so I decided to download and install the latest SDK. Unfortunately, this seemingly minor update presented a major failure in my debug [...]]]></description>
			<content:encoded><![CDATA[<p>I finally updated to Xcode 3.2.3. I was a little late because I had other priorities, but I wanted to get my iPhone projects building and installing onto my iPhone OS 4.0 devices, so I decided to download and install the latest SDK.</p>
<p>Unfortunately, this seemingly minor update presented a major failure in my debug builds, which I&#8217;m adventurously compiling using the LLVM clang compiler. They built fine with Xcode 3.2.2, but starting in 3.2.3, I got a linkage failure, tracing back to the popular open source <a href="http://regexkit.sourceforge.net/RegexKitLite/">RegExKitLite</a>:</p>
<pre>
Undefined symbols:
  "___gxx_personality_v0", referenced from:
      _rkl_debugCacheSpinLock in RegexKitLite.o
      ...
  "__ZSt9terminatev", referenced from:
      +[NSString(RegexKitLiteAdditions) clearStringCache]
      in RegexKitLite.o
</pre>
<p>What? Those symbols smack of C++, but there isn&#8217;t any C++ code in my project. At least, I don&#8217;t think there is. RegExKitLite is so famously <em>advanced</em> in its designed, I couldn&#8217;t easily tell you whether there was stuff in there intended as C++ or not. On a whim, I tried to switch the file type to C++ to see if that made clang any happier. No, it screamed bloody murder. It agrees with me, RegExKitLite is <em>not</em> C++ code.</p>
<p>So why the link errors? I examined the compile line carefully for RegExKitLite and confirmed that it&#8217;s using clang in a manner that should only be generating plain C linkage:</p>
<pre>
/Developer/usr/bin/clang -x objective-c -arch x86_64 ...
</pre>
<p>But when I look at the resulting RegExKitLite.o with the &#8220;nm&#8221; command-line tool, it shows the culprits symbols have been listed as references in the binary object file:</p>
<pre>
% nm RegexKitLite.o | grep -e terminate\\\|personality
                 U __ZSt9terminatev
                 U ___gxx_personality_v0
</pre>
<p>Normally when I&#8217;m getting some kind of issue like this, I just type in the problematic symbols in to Google and usually find somebody else has found and solved the problem. No such luck this time. There are lots of false positives for the typical reason somebody runs into this link error: they are compiling legitimate C++ code but neglecting to link with the stdc++ library. But in our case, we are <em>not compiling C++ code</em>, but we&#8217;re ending up with C++ dependencies nonetheless.</p>
<p>I hopped on to the #clang IRC channel on irc.oftc.net, where a couple extremely helpful clang engineers (thanks to dgregor and rjmccall) helped talk me through the problem, and determine that it does seem to be a clang 1.5 bug. They confirmed that with their latest and greatest clang the bug seems to be fixed, but I was curious to confirm it myself, so I <a href="http://clang.llvm.org/get_started.html#build">checked out and built</a> the latest clang, too. Sure enough, all is well for future generations!</p>
<p>But what do we do now, stuck with the clang 1.5 that ships with Xcode? There is a crude workaround: simply link to stdc++. But yuck! All that C++ linkage dirtying up my pristine Objective-C project? Since I only use clang (for now) to build debug builds, I don&#8217;t have too much of a problem doing this. But if I was shipping these binaries I would be very hesitant to make that concession.</p>
<p>Radar #<a href="rdar://problem/8230225">8230225</a>: clang 1.5 forces linkage to C++ for non-C++ source file<br />
(<a href="http://openradar.appspot.com/8230225">Open Radar Link</a>)</p>
<p>The best we can do is report the issue to Apple and let them decide whether it&#8217;s worth their time to backport whatever fix in later clang is missing from clang 1.5. If you have other suggestions for how to work around the problem in the mean time, please do chime in with a comment below.</p>
<p><strong>Update:</strong> The author of RegExKitLite kindly chimed in below with a pointer to the <a href="http://llvm.org/viewvc/llvm-project?view=rev&#038;revision=103938">revision</a> in the clang source repository that that fixes the issue. He also suggests a simple, and seemingly safe workaround, involving a slight tweak to the RegExKitLite source code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.red-sweater.com/blog/1345/regexkit-clang/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Fast Unit Testing Iterations</title>
		<link>http://www.red-sweater.com/blog/779/fast-unit-testing-iterations</link>
		<comments>http://www.red-sweater.com/blog/779/fast-unit-testing-iterations#comments</comments>
		<pubDate>Tue, 31 Mar 2009 19:59:25 +0000</pubDate>
		<dc:creator>Daniel Jalkut</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://www.red-sweater.com/blog/?p=779</guid>
		<description><![CDATA[It&#8217;s not as though unit testing is completely new to me, but even years after I wrote my first tests, I still consider myself a naive amateur in many regards. I&#8217;ve been ramping up my use of tests lately thanks in large part to a technique I read about in Michael Feathers&#8217;s book Working Effectively [...]]]></description>
			<content:encoded><![CDATA[<p>
 It&#8217;s not as though unit testing is completely new to me, but even years after I wrote my first tests, I still consider myself a naive amateur in many regards. I&#8217;ve been ramping up my use of tests lately thanks in large part to a technique I read about in Michael Feathers&#8217;s book <a href="http://www.amazon.com/gp/product/0131177052?ie=UTF8&#038;tag=redsweater-20">Working Effectively With Legacy Code</a>.
</p>
<p>
Essentially, the idea is that before you do any major refactoring in your existing code base, you should attempt to locate a &#8220;bottleneck&#8221; to how that code is reached, and test the interface at that bottleneck.  So, if all the code paths to Class A and Class B are through Class C, I can effectively just cover Class C with unit tests and be relatively certain that the functionality of Classes A and B are covered to the extent that I care about them.
</p>
<p>
Refactoring then becomes <em>a lot less stressful</em>, because you&#8217;re more likely to catch stupid mistakes and changes in functionality you might cause in the process. I realize that no set of tests is a guarantee against introducing new bugs, but in the process of covering classes with test coverage, you also end up learning quite a bit about what the classes actually do.  This is no small victory when working with code that you either didn&#8217;t write, or that you haven&#8217;t reviewed in a number of years.
</p>
<p>
As I&#8217;ve become more and more dedicated to testing in my Mac and iPhone projects, the size of my test suites has grown.  I&#8217;m subscribing to guidelines for good test writing: that they should be fast and as isolated as possible. But they still take a non-trivial amount of time to run.  It&#8217;s gotten to the point where the tests for my &#8220;web publishing frameworks&#8221; take at least a minute to run on my MacBook.  This is pretty fast in the big scheme of things, but a long time to wait when I&#8217;m engaged in a rapid edit, build, and test iteration.
</p>
<p>
I figured there must be some way to limit the test cases that get run to just the specific one I&#8217;m working on at the moment. And it turns out there is. Thanks to the &#8220;Other Test Flags&#8221; build setting in Xcode, I can temporarily change the behavior so that it runs only a subset of all the tests contained in my test bundle. For example, right now I&#8217;m working on tests that cover the functionality of my RSRESTCall class:
</p>
<p>
<img src="http://www.red-sweater.com/blog/images/OtherTestFlags-20090331-155415.jpg" />
</p>
<p>
The -SenTest option is passed on to the test rig, in my case the default &#8220;otest&#8221; command that comes with Xcode. This lets the test rig know that instead of the default behavior of finding and running every test in the bundle, it should just run the tests in the &#8220;RSRestCallTests&#8221; SenTestCase subclass.
</p>
<p>
Something I didn&#8217;t mention yet but which is also aiding me greatly in the measuring my test coverage is the &#8220;gcov&#8221; library that also comes bundled with Apple&#8217;s developer tools. I&#8217;m using this to create a &#8220;Code Coverage&#8221; build of my code, that makes it possible to see exactly which lines of code did or did not get run during a particular set of tests.  This, in conjunction with <a href="http://code.google.com/p/coverstory/">a cool application</a> from Google&#8217;s Mac developers, makes it pretty easy for me to seek out uncovered areas of code, think about how to cover them with tests, and iterate.
</p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.red-sweater.com/blog/779/fast-unit-testing-iterations/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Unit Testing Roadblocks</title>
		<link>http://www.red-sweater.com/blog/536/unit-testing-roadblocks</link>
		<comments>http://www.red-sweater.com/blog/536/unit-testing-roadblocks#comments</comments>
		<pubDate>Fri, 01 Aug 2008 17:49:26 +0000</pubDate>
		<dc:creator>Daniel Jalkut</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://www.red-sweater.com/blog/?p=536</guid>
		<description><![CDATA[Unit testing is a good idea. Ask any random developer what they think about unit testing and you&#8217;re likely to get one of four responses: I don&#8217;t know what they are. I love them! You should always use them! I hate them! You should never use them! I appreciate them, but I&#8217;m lazy and don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>Unit testing is a good idea. Ask any random developer what they think about unit testing and you&#8217;re likely to get one of four responses:</p>
<ol>
<li>I don&#8217;t know what they are.</li>
<li>I love them! You should <em>always</em> use them!</li>
<li>I hate them! You should <em>never</em> use them!</li>
<li>I appreciate them, but I&#8217;m lazy and don&#8217;t use them that much.
</li>
</ol>
<p>
Of these, I have the most respect for the first and fourth. If you don&#8217;t know what unit testing is, you can hardly be blamed for failing to employ them. Go <a href="http://en.wikipedia.org/wiki/Unit_testing">learn more about them</a> and maybe you&#8217;ll enjoy the rest of this entry a bit more. If you are familiar with them but feel that you don&#8217;t use them enough, don&#8217;t beat yourself up. You&#8217;re probably using them &#8220;about the right amount.&#8221; That is to say, as much as you need to, in order to alleviate your pains.
</p>
<p>
Groups 2 and 3 could practically be folded into one, because each is about as useless the other. Some things in life demand a strict behavioral code, but programming is not one of them. Some kinds of code bases and programming tasks are extremely conducive to unit testing, and others are not. Use them wherever they make sense, and where they accelerate your ability to improve upon your existing code base. I won&#8217;t go into much more about the whens and ifs, but <a href="http://www.wilshipley.com/blog/2005/09/unit-testing-is-teh-suck-urr.html">Wil Shipley</a> and <a href="http://www.friday.com/bbum/2005/09/24/unit-testing/">Bill Bumgarner</a> have delved deeper into this question, if you&#8217;re interested in reading more.
</p>
<p><h3>Laziness Incubators</h3>
</p>
<p>
Let&#8217;s assume for the sake of argument that you&#8217;ve learned about unit testing, and self-disqualified yourself from either of the extremist groups described above. You probably find yourself in that fuzzy group that I&#8217;ve labeled lazy yet appreciative. Laziness on its own is one thing, but it doesn&#8217;t help when tedious roadblocks are put in our way to incubate further laziness.
</p>
<p>
<strong>&#8220;I should really add a unit test suite for this complicated class.&#8221;</strong>
</p>
<p>
&#8230;
</p>
<p>
<strong>&#8220;But then I&#8217;d have to create a new unit test file, and stuff&#8230;&#8221;</strong>
</p>
<p>
I&#8217;m ashamed to admit that this is how many a unit test has been put off. Other laziness incubators include the friction of adding a suitable unit test bundle target to a project, and the difficulty of deciding how to factor your unit tests so that they make sense in the context of your project. Oh, and let&#8217;s not overlook the difficulty of having to think up how to write the specific unit tests themselves.
</p>
<p>
Apple makes some of these roadblocks somewhat easier, with <a href="http://developer.apple.com/documentation/DeveloperTools/Conceptual/UnitTesting/UnitTesting.html">built-in unit testing support</a> for Xcode. Unfortunately, they only go about 80% of the way in many regards, leaving us floundering to figure out how to fill the gaps for the remaining assistance we might need. These gaps where we&#8217;re forced to scramble for solutions can be a great deterrent to using unit tests as much as we might like.
</p>
<p><h3>Debugging Unit Tests</h3>
</p>
<p>
So you&#8217;ve overcome inertia and established unit testing build targets in your projects. You came up with an approach that makes sense for your code, created a new unit test suite source file, and actually written a few tests for your code. But now you&#8217;re bound to run into a vexing question: <strong>&#8220;how the heck do I debug this thing?&#8221;</strong>. Since unit tests are generally built into a standalone bundle, there&#8217;s nothing for Xcode to run. But when you come across a failing unit test and you can&#8217;t figure out why, you find yourself wishing you could step through the code just as you might in an application.
</p>
<p>
The answer to this question, as well as many other &#8220;missing pieces&#8221; for unit test support in Xcode, comes from Chris Hanson, who shares a great deal of useful information on his blog, including this gem on <a href="http://chanson.livejournal.com/120740.html">debugging unit tests</a>. This post also contains a number of useful links if you&#8217;re still struggling with the other roadblocks such as adding a target, etc.
</p>
<p>
What we learn from Chris is essentially that the easiest way to debug unit tests in your project is to set up some executable, <em>any executable</em>, and arrange for your unit test bundle to be &#8220;injected&#8221; into the executable at runtime. Now, to debug your unit tests, you just ask Xcode to debug the injected executable.
</p>
<p>
It turns out this isn&#8217;t very difficult, but it&#8217;s tedious. To set up this custom executable, you need to add a bunch of cryptic command line arguments and environment variables to your project. Yuck! This cumbersome  process has caused me on many occasions to &#8220;just skip doing unit tests for now.&#8221; That&#8217;s not really helpful to me or to the health of my code, so I finally got off by butt and wrote a handy AppleScript to do it for me:
</p>
<p>
Download <a href="http://www.red-sweater.com/AppleScript/AddUnitTestExecutable.zip">Add Unit Test Executable</a>. Free AppleScript.
</p>
<p>
What does this script do? In a nutshell, it asks for the name of your unit test bundle. Provide it, without the &#8220;.octest&#8221; extention, and the script will add a custom executable to your application, with all the gross arguments and environment variables needed to &#8220;make it work&#8221; in both Xcode 3 and Xcode 3.1. I added it to my Xcode application-specific scripts folder, and select it (using <a href="http://www.red-sweater.com/fastscripts/">FastScripts</a>) whenever I find myself in a project that doesn&#8217;t already have a suitable custom executable for debugging unit tests.
</p>
<p>
My script uses TextEdit.app as the test harness application, because it&#8217;s on everybody&#8217;s Mac, and because it seems like a fairly innocuous host application. Of course, you could use your own application, or another custom host application of your choosing. Just edit the script to suit your needs.
</p>
<p>
Hope this helps some of you overcome one source of laziness getting in the way of writing excellent unit tests!</p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.red-sweater.com/blog/536/unit-testing-roadblocks/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Crappy Crash Logs</title>
		<link>http://www.red-sweater.com/blog/439/crappy-crash-logs</link>
		<comments>http://www.red-sweater.com/blog/439/crappy-crash-logs#comments</comments>
		<pubDate>Thu, 06 Dec 2007 19:47:07 +0000</pubDate>
		<dc:creator>Daniel Jalkut</dc:creator>
				<category><![CDATA[Carbon]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://www.red-sweater.com/blog/439/crappy-crash-logs</guid>
		<description><![CDATA[Developers who write code inevitably write code that crashes. Luckily for our users, 99% of those crashes happen on our own development machines, and we get the opportunity to fix them before shipping them off to our unsuspecting computers. But every once in a while even the most polished and refined software exhibits that nastiest [...]]]></description>
			<content:encoded><![CDATA[<p>Developers who write code inevitably write code that crashes. Luckily for our users, 99% of those crashes happen on our own development machines, and we get the opportunity to fix them before shipping them off to our unsuspecting computers.</p>
<p>
But every once in a while even the most polished and refined software exhibits that nastiest of malfunctions: the crashing bug. In the middle of a possibly important user task, the application comes screeching to a halt and disappears, leaving the user with nothing more than a cryptic message from the operating system, along with an offer to send the crash log off to Apple.
</p>
<p>
<img src="http://www.red-sweater.com/blog/images/CrashDialog-20071206-131213.jpg" />
</p>
<p>
Needless to say, crashes suck. A lot. For users, especially. If there&#8217;s one behavior of your application that you should focus on eliminating, it&#8217;s the behavior of crashing. Above all other &#8220;nuisances,&#8221; this is the one that is absolutely unacceptable.
</p>
<p>
Which is why crash logs are so important. Occasionally, when a user is sophisticated enough to understand the value of the crash log and, instead of choosing to send it to Apple, copies and pastes it into an email to you, you should be overjoyed! Finally! A  crash has been captured in the wild and delivered to you for easy inspection. This artifact not only proves that a crashing bug exists, but usually includes highly detailed information about where and how the crash has happened.
</p>
<p>
Which is why it boggles the mind to think that some developers see these crash logs as relatively useless. In my own experience of reporting bugs to other developers, I have found frequently that my crash log is considered more as a statistic than as a specimen. While I expect a response like &#8220;great, I see what the bug is, and I&#8217;ll get this fixed,&#8221; I often get responses more like &#8220;sigh, I&#8217;ve seen this a few times but have no idea what&#8217;s going on!&#8221;
</p>
<p>
Sometimes I find that the developer in question simply needs to be educated about the tools at his or her disposal. I imagine the hours wasted speculating about what the crash log means, and can&#8217;t help but think if they knew how to analyze it, they  could have the bug solved (in many cases) in moments. Oh &#8211; and I&#8217;m sounding high and mighty right now, so before I get too carried away, let me just say that <em>I too need to be educated on a great many things</em>, but making sense of crash logs is not particularly high on that list. I leave it to other bloggers to fill in the gaps of my education.</p>
<h3>Crash Logs: The Crappy Way</h3>
</p>
<p>
So what is this big thing that developers are missing? Well, a crash log essentially shows the &#8220;path&#8221; that the little hamsters in your computer were running on when they fell off the cliff. It paints a picture of where the program got misguided and went off doing something it never should have done. Problem is, the picture is a little blurry. Below is an actual crash log submitted by an actual MarsEdit user (abbreviated and condensed to fit the blog):
</p>
<p><pre style="font-size:1em;">
Thread 0 Crashed:
Foundation 0x93cc2a2e _NSAPAddPage + 94
Foundation 0x93cc3b27 __NSAutoreleaseObject + 263
Foundation 0x93cc3962 -[NSObject(NSObject) autorelease] + 18
Foundation 0x93cceaca +[NSString stringWithFormat:] + 106
marsedit   0x000637fb 0x1000 + 403451
marsedit   0x00053883 0x1000 + 338051
marsedit   0x000539ea 0x1000 + 338410
marsedit   0x00053d7b 0x1000 + 339323
marsedit   0x00053e45 0x1000 + 339525
marsedit   0x0005238b 0x1000 + 332683
</pre>
</p>
<p>
For any non-programmers who are still reading (bravi!), you may have a little trouble understanding what the heck this means. This is an ordered description of the path the computer followed while trying to do <em>something</em>. Problem is it ended up crashing. The path is shown in reverse-order, so the crash is at the top of the list, inside Foundation (an Apple system library). Trying to make human sense of this goes something like this:
</p>
<ol>
<li>Something in MarsEdit at address 0x0005238b&#8230;</li>
<li>&#8230; called something in MarsEdit at address 0x00053e45 </li>
<li>&#8230; called something in MarsEdit at address 0x00053d7b </li>
<li>&#8230; called something in MarsEdit at address 0x000539ea </li>
<li>&#8230; called something in MarsEdit at address 0&#215;00053883 </li>
<li>&#8230; called something in MarsEdit at address 0x000637fb </li>
<li>&#8230; which called a standard string library method &#8220;stringWithFormat&#8221;</li>
<li>which eventually crashed in the system.</li>
</ol>
<p>
You can sort of see how some developers are forced to throw up their arms in despair, right? But what if you could turn this muddled picture into something a bit sharper? The fact is, you can. The reason the picture is so blurry is because MarsEdit shipped without debugging symbols. The reasons for this are mostly to keep the shipping application as small as possible, but there are also some good reasons to hide the symbols if they reveal too much about your business strategy.</p>
<h3>Crash Logs: The Happy Way</h3>
</p>
<p>
Many developers seem to think that gathering useful crash logs requires shipping a symbol-laden application, but aren&#8217;t willing to do so. The fact is, you can have the best of both worlds by shipping a symbol-stripped version of your application, but <em>keeping a symbol-laden version</em> on-hand for the developer&#8217;s convenience.
</p>
<p>
What am I getting at? Apple offers a tool called &#8220;atos&#8221;, which makes it relatively easy to map an address from a symbol-stripped application to a name in a symbol-laden version of that same application.  As long as the two applications were built with the same sources and using the same build options, the addresses are bound to match up. It&#8217;s just the symbols that are &#8220;stripped&#8221; from the shipping application.
</p>
<p>
Let&#8217;s take a look at what happens when I apply my atos powers to the crash log I pasted above. From the Terminal, I invoke atos with the literal memory addresses of all the mysterious points in the &#8220;path&#8221; from the crash log. You can list the addresses in whatever order you want, but I&#8217;m listing them so that the result will be in order from top to bottom, the same way I reasoned out the crash in plain &#8220;crappy&#8221; English above:
</p>
<p><pre style="font-size:1em;">
iBook> cd MarsEdit.app/Contents/MacOS
iBook> atos -arch i386 -o MarsEdit \
	0x0005238b 0x00053e45 0x00053d7b 0x000539ea 0x00053883 0x000637fb
</pre>
</p>
<p>
Note also that I specified the architecture explicitly. This is because I am debugging this on a PowerPC Mac, but the crash log I received showed that the customer is running on an Intel machine. This yields a magical response with, behold, real meaningful symbols!</p>
<pre style="font-size:1em;">
-[RSXMLRPCCall invoke:] (in MarsEdit) (RSXMLRPCCall.m:397)
-[RSXMLRPCRequest requestText] (in MarsEdit) (RSXMLRPCRequest.m:239)
-[RSXMLRPCRequest serializeParams:] (in MarsEdit) (RSXMLRPCRequest.m:216)
-[RSXMLRPCRequest serializeDictionary:toString:] (in MarsEdit) (RSXMLRPCRequest.m:153)
-[RSXMLRPCRequest serializeData:toString:] (in MarsEdit) (RSXMLRPCRequest.m:123)
-[NSData(extras) base64StringWithLineLength:] (in MarsEdit) (NSData+extras.m:215)
</pre>
</p>
<p>
Now I can apply my human sense again, but with the  benefit of symbolic names instead of raw memory addresses:
</p>
<ol>
<li>MarsEdit invoked an RPC network request</li>
<li>&#8230; which while building the actual request cargo text</li>
<li>&#8230; was trying to serialize the parameters</li>
<li>&#8230; when it tried to serialize a dictionary object</li>
<li>&#8230; whose data</li>
<li>&#8230; upon being converted to a Base64 representation</li>
<li>&#8230; caused a &#8220;stringWithFormat:&#8221; call that went blammo!</li>
</ol>
<p>
Not only does the plot to this story make a lot more sense now, but I&#8217;ve even got handy pointers to the line numbers in the source code. Let&#8217;s see, NSData+extras.m, around line 215:
</p>
<p><pre style="font-size:1em;">
NSString *charString = [NSString stringWithFormat:@"%c", base64EncodingTable [outbuf [i]]];
</pre>
</p>
<p>
Survey says? That&#8217;s the line I&#8217;m going to zero in on now as I try to figure out <em>why</em> this crash is occurring. Sure, I&#8217;ll have to now speculate as to why, and under what circumstances the observed crash might occur. So the magic of &#8220;atos&#8221; doesn&#8217;t take all the work out of debugging a crash log, but it brings most crashes out of the &#8220;frustratingly impossible&#8221; into the realm of &#8220;all in a day&#8217;s work.&#8221; I can use my knowledge of the situation to ask intelligent questions of the user, and hopefully get to the bottom of it, so that no other user ever has to see the nasty crash again.
</p>
<p>
I can do more than just tell the user &#8220;thanks for the report, I have no clue what&#8217;s happening here. Sorry.&#8221;</p>
<h3>Doing It For Yourself</h3>
</p>
<p>
I hope I&#8217;ve intrigued you by the power of what I was able to achieve with &#8220;atos&#8221;, but of course to do the same with your own project, you&#8217;ll need to make sure you can come up with a &#8220;symbol-laden version&#8221; of your release app, so you can apply the same magic. The best way I know to do this is to simply add another build configuration in xcode, that is just like your &#8220;Release&#8221; configuration, but doesn&#8217;t strip out debugging symbols. You can read more about this approach and others in <a href="http://developer.apple.com/tools/xcode/symbolizingcrashdumps.html">Apple&#8217;s fine documentation</a>.
</p>
<p>
If you find yourself dealing with crash logs on a regular basis, it might be a good idea to make building a &#8220;symbol-laden&#8221; version of your app part of the standard build and distribute process. For myself, I&#8217;ve found it happens rarely enough that I&#8217;m happy with a process whereby I re-checkout a tagged version of the sources from Subversion, and then rebuild a copy using the &#8220;Release With Symbols&#8221; build configuration.
</p>
<p>
Nota Bene: If you&#8217;re on Leopard and trying to replicate a symbol-laden version of an app you shipped with Tiger, you&#8217;ll probably have to tweak Xcode to use the old linker, in order to get a build whose memory addresses match up with your old Tiger-built application. Might be easier to just go back to Tiger and rebuild it there.
</p>
<p>
I know this was probably common knowledge for some of you, but I also know from experience of chatting with my colleagues that this is completely new, forehead-slapping &#8220;why didn&#8217;t I know about that?!&#8221; type material for many others. I hope it saves you hours of work. Possibly even enough hours to continue reading long articles such as this one!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.red-sweater.com/blog/439/crappy-crash-logs/feed</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Mac Developer Network Launches</title>
		<link>http://www.red-sweater.com/blog/436/mac-developer-network-launches</link>
		<comments>http://www.red-sweater.com/blog/436/mac-developer-network-launches#comments</comments>
		<pubDate>Thu, 22 Nov 2007 00:42:10 +0000</pubDate>
		<dc:creator>Daniel Jalkut</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Links]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://www.red-sweater.com/blog/436/mac-developer-network-launches</guid>
		<description><![CDATA[Our friend Scotty, who is responsible for the Late Night Cocoa podcast, has just expanded his offerings, launching a &#8220;network&#8221; of Mac developer related podcasts and web content. The second podcast in the lineup is a roundtable format, such as you might hear on such excellent shows at Leo Laporte&#8217;s MacBreak Weekly and This Week [...]]]></description>
			<content:encoded><![CDATA[<p>Our friend Scotty, who is responsible for the <a href="http://www.macdevnet.com/index.php?option=com_content&#038;view=category&#038;layout=blog&#038;id=37&#038;Itemid=160">Late Night Cocoa</a> podcast, has just expanded his offerings, launching a &#8220;network&#8221; of Mac developer related podcasts and web content. The second podcast in the lineup is  a roundtable format, such as you might hear on such excellent shows at Leo Laporte&#8217;s <a href="http://twit.tv./mbw">MacBreak Weekly</a> and <a href="http://twit.tv./twit">This Week in Tech</a>.</p>
<p>
The podcast is called the Mac Developer Roundtable, and I felt honored to be invited to participate for the first episode. We recorded it a week or two ago, and it has just gone live:
</p>
<p>
<a href="http://www.macdevnet.com/index.php?option=com_content&#038;view=article&#038;id=113%3Amdr001&#038;Itemid=161">Mac Developer Roundtable Episode 1</a>
</p>
<p>
In this first episode, we all chatted about Leopard and in particular what&#8217;s new and exciting for developers. Tune in to hear the collected wisdom of <a href="http://www.connectedflow.com/blog/">Fraser Speirs</a>, <a href="http://www.zathras.de/angelweb/home.htm">Uli Kusterer</a>, <a href="http://www.zarrastudios.com/ZDS/Blog/Blog.html">Marcus Zarra</a>, and of course our host Scotty.
</p>
<p>
One question I raised in the show was whether the new &#8220;ibtool&#8221; (formerly nibtool) in Leopard makes the whole process of automated localization any easier. To be honest, I resist localized versions for many of my applications largely because the hassle of integrating localization updates has always seemed really awkward to me. I&#8217;d love to get into a position where I could easily integrate updates to localizations without having to hand tweak things all the time. I know there are some existing solutions using nibtool but I wonder if things have gotten even better in Leopard?
</p>
<p>
Got any great localization techniques to share?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.red-sweater.com/blog/436/mac-developer-network-launches/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Brent Simmons On Large Cocoa Projects</title>
		<link>http://www.red-sweater.com/blog/331/brent-simmons-on-large-cocoa-projects</link>
		<comments>http://www.red-sweater.com/blog/331/brent-simmons-on-large-cocoa-projects#comments</comments>
		<pubDate>Wed, 25 Apr 2007 23:48:19 +0000</pubDate>
		<dc:creator>Daniel Jalkut</dc:creator>
				<category><![CDATA[Links]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://www.red-sweater.com/blog/331/brent-simmons-on-large-cocoa-projects</guid>
		<description><![CDATA[Brent Simmons shares a good deal of wisdom in his post about managing a large-ish Cocoa project. In particular he&#8217;s referring to NetNewsWire, but his advice is especially pertinent to me now that I own and maintain a rather substantial number of source files that were designed and authored by Brent (MarsEdit, for anybody late [...]]]></description>
			<content:encoded><![CDATA[<p>Brent Simmons shares a good deal of wisdom in <a href="http://inessential.com/?comments=1&amp;postid=3405">his post</a> about managing a large-ish Cocoa project. In particular he&#8217;s referring to <a href="http://www.newsgator.com/NGOLProduct.aspx?ProdID=NetNewsWire">NetNewsWire</a>, but his advice is especially pertinent to me now that I own and maintain a rather substantial number of source files that were designed and authored by Brent (<a href="http://www.red-sweater.com/marsedit/">MarsEdit</a>, for anybody late to the party).</p>
<p>
I love the emphasis on &#8220;researchability.&#8221; He points to the fact that projects of a certain size become impossible to keep in your head. So when you go to work on any particular subsection of the app, you need to be confident that you&#8217;ll find your balance quickly so you can get on with your work.
</p>
<p>
In particular, I liked the suggestion that weak binding in the form of notifications or key-value observing can be detrimental to researchability. Brent notes that the weak binding makes it difficult to mentally follow the source code, so it can be prudent to strongly bind classes that are otherwise useless without each other.
</p>
<p>
He also reminds us of some good IDE habits for maintaining code. I was glad to be reminded that the function popup in Xcode is keyboard invokable (as Brent says, &#8220;Every time you touch the mouse, God kills a kitten.&#8221;). This is very cool because with keyboard navigation of the menu you can quickly jump to a method by name.
</p>
<p>
Another tip he reminds us about is the &#8220;Open Quickly&#8221; option (cmd-shift-D). I use this feature frequently, but not in the way he describes. It&#8217;s infuriating that when you want to &#8220;open quickly,&#8221; the dialog for typing in the name of a source file doesn&#8217;t tab-complete. Imagine how much more powerful it would be if you could type &#8220;MyPic&lt;tab>&#8221; and get &#8220;MyPictureThingyController.h&#8221;. Having to type the whole name of a file in removes most of the quickness. When I use the shortcut, I do so with the cursor inside the quotes or brackets of an include line. When invoked in this context, Xcode is smart and just jumps to the desired header file.
</p>
<p>
<strong>Update:</strong> Quentin over at Rogue Amoeba noticed this shortcoming a long time ago, and developed an Xcode plugin to address the problem. Check out <a href="http://www.rogueamoeba.com/utm/posts/Random/XcodeOpenQuicker-2007-04-26-14-17">Xcode Open Quicker</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.red-sweater.com/blog/331/brent-simmons-on-large-cocoa-projects/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Abusing Objective C With Class</title>
		<link>http://www.red-sweater.com/blog/320/abusing-objective-c-with-class</link>
		<comments>http://www.red-sweater.com/blog/320/abusing-objective-c-with-class#comments</comments>
		<pubDate>Thu, 12 Apr 2007 21:20:23 +0000</pubDate>
		<dc:creator>Daniel Jalkut</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://www.red-sweater.com/blog/320/abusing-objective-c-with-class</guid>
		<description><![CDATA[Dynamic messaging is one of the nifty features of Cocoa and Objective-C programming on the Mac. You don&#8217;t have to know which class, or even which method your code will call until runtime. The feature is utilized a great deal by the delegation pattern employed by most standard classes in AppKit. For instance, when a [...]]]></description>
			<content:encoded><![CDATA[<p>Dynamic messaging is one of the nifty features of Cocoa and Objective-C programming on the Mac. You don&#8217;t have to know which class, or even which method your code will call until runtime. The feature is utilized a great deal by the delegation pattern employed by most standard classes in AppKit. For instance, when a window is threatening to close, Apple yields the final decision making to a delegate method, if present:</p>
<p><pre style="font-size:1.0em;">
<code>
- (BOOL) windowShouldClose:(id)sender;
</code>
</pre>
</p>
<p>
If you implement this delegate method and return NO for a particular window, then the user&#8217;s attempts to close it are thwarted (hopefully because you just did something friendly like ask them if they were sure or not).
</p>
<p>
If we&#8217;re agreed that delegation and dynamic messaging are a good idea, we should be prepared to use them in our own code as well. Let&#8217;s say we&#8217;re writing a custom class where delegation of this kind would be useful. We&#8217;d like to be as much like Apple as possible, to further solidify the patterns that we all use on a regular basis.
</p>
<p>
My example application is a coffee maker, and it makes coffee at regular intervals unless the delegate method believes it should not:
</p>
<p><pre style="font-size:1.0em;">
<code>
- (BOOL) coffeeMaker:(RSCoffeeMaker*)theMaker
	shouldBrewForScheduledDate:(NSDate*)scheduledDate;
</code>
</pre>
</p>
<p>
What must the code in the coffee maker do in order to satisfy this contract? The &#8220;scheduledBrewTimerFired:&#8221; method might look something like this:
</p>
<p><pre style="font-size:1.0em;">
<code>
- (void) scheduledBrewTimerFired:(NSTimer*)brewTimer
{
	BOOL shouldBrew = YES;

	// Give the delegate a chance to reject
	SEL delSelector =
		@selector(coffeeMaker:shouldBrewForScheduledDate:);

	if ((mDelegate != nil) &#038;&#038;
		([mDelegate respondsToSelector:delSelector] == YES))
	{
		shouldBrew = [mDelegate performSelector:delSelector
			withObject:self
			withObject:[brewTimer fireDate]];
	}

	if (shouldBrew == YES)
	{
		//...
	}
}
</code>
</pre>
</p>
<p>
Nifty, right? Yes, nifty. But wrong. What&#8217;s the problem? It&#8217;s that line where performSelector is called. If you have as many warnings turned on as you should, you&#8217;ll see something along the lines of &#8220;<em>warning: assignment makes integer from pointer without a cast</em>.&#8221; The reason? The performSelector method returns an &#8220;id&#8221;, not a &#8220;BOOL&#8221;. We&#8217;re expecting magic to happen here, and those of us who grew comfortable with the nuances of PowerPC-based calling conventions have seen magic happen here more often than is healthy.
</p>
<p>
By violating the function prototype for performSelector, we&#8217;re robbing the compiler of its ability to accurately produce assembly code that retrieves the BOOL return type correctly. That means we&#8217;ll get the wrong answer some percentage of the time, where that percentage is determined by the degree to which <em>BOOL</em> and <em>id</em> return types are handled differently on the platform.
</p>
<p>
My first instinct in addressing this problem was to go down a layer. Surely if performSelector is using an unsatisfactory prototype, I could just drop down to objc_msgSend and handle the messaging myself. But alas! The lower-level function <em>also</em> returns an id. At this level, there are some special functions such as objc_msgSend_stret, which messages an object and returns a <em>structure</em>, but there isn&#8217;t a handy objc_msgSend_boolret for our convenience.
</p>
<p>
So what&#8217;s a conscientous developer to do? I was lucky to discover a <a href="http://www.cocoabuilder.com/archive/message/cocoa/2006/2/12/156604">mailing-list thread</a>, in which the answer to this question was beautifully outlined by Greg Parker of Apple. Credit also goes to Rosyna of Unsanity, for asking the question that led to Greg&#8217;s answer. Rosyna later expressed appreciation in a <a href="http://www.unsanity.org/archives/haxies/universally_fat_1.php">follow-up post</a>.
</p>
<p>
So what&#8217;s the trick? In order to get the freedom of dynamic messaging combined with the complete cooperation of the compiler, we need to define a custom function pointer. This points to the same address in memory as the objc_msgSend function, but is defined with a differing prototype. This way we get the message delivery functionality of the Objective-C runtime, while letting the compiler in on the fact that the method being messaged will in fact return a BOOL typed response.
</p>
<p><pre style="font-size:1.0em;">
<code>
#import &lt;objc/objc-runtime.h>

- (void) scheduledBrewTimerFired:(NSTimer*)brewTimer
{
	bool shouldBrew = YES;

	// Give the delegate a chance to reject
	SEL delSelector =
		@selector(coffeeMaker:shouldBrewForScheduledDate:);
	if ((mDelegate != nil) &#038;&#038;
		([mDelegate respondsToSelector:delSelector] == YES))
	{
		// Give the compiler a clue - courtesy of Greg Parker
		BOOL (*MyMagicSender)(id, SEL, id, id) =
			(BOOL (*)(id, SEL, id, id)) objc_msgSend;

		shouldBrew = MyMagicSender(mDelegate, delSelector,
			self, [brewTimer fireDate]);
	}

	if (shouldBrew == YES)
	{
		//...
	}
}
</code>
</pre>
</p>
<p>
Nifty, right? And correct, too. Enjoy!
</p>
<p>
<strong>Update:</strong> <a href="http://www.noodlesoft.com/blog/">Paul Kim</a> via chat, and Jan Van Boghout in the comments below each noticed a flaw in my contrived example. Since I already know the selector I&#8217;m planning to call, I could just define it explicitly with a regular Objective-C method prototype. Then the compiler would know exactly how to generate the code if I called the delegate directly:</p>
<pre>
<code>
shouldBrew = [mDelegate coffeeMaker:self
	shouldBrewForScheduledDate:[brewTimer fireDate]];
</code></pre>
</p>
<p>
That&#8217;s true, and it&#8217;s a fault in my overly-contrived example. But imagine a more dynamic scenario, where the prototype of the method is known, but not the selector. For instance, if the class offers clients the ability to specify a selector:</p>
<pre>
<code>
- (void) scheduleBrewingAtDate:(NSDate*)brewDate
	withBrewDelegate:(id)brewDelegate
	withDelegateSelector:(SEL)delSel;
</code>
</pre></p>
]]></content:encoded>
			<wfw:commentRss>http://www.red-sweater.com/blog/320/abusing-objective-c-with-class/feed</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Hexy Little Thing</title>
		<link>http://www.red-sweater.com/blog/279/hexy-little-thing</link>
		<comments>http://www.red-sweater.com/blog/279/hexy-little-thing#comments</comments>
		<pubDate>Wed, 14 Feb 2007 18:59:08 +0000</pubDate>
		<dc:creator>Daniel Jalkut</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Free Code]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://www.red-sweater.com/blog/279/hexy-little-thing</guid>
		<description><![CDATA[I&#8217;m working on an application now that uses a custom document format. Since my code manipulates this format and spits it back out to disk, I find myself frequently examining the resulting documents using Peter Ammon&#8217;s excellent Hex Fiend to examine the resulting files, and make sure the content is still format-compliant. But while I&#8217;m [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working on an application now that uses a custom document format. Since my code manipulates this format and spits it back out to disk, I find myself frequently examining the resulting documents using Peter Ammon&#8217;s excellent <a href="http://ridiculousfish.com/hexfiend/">Hex Fiend</a> to examine the resulting files, and make sure the content is still format-compliant.</p>
<p>
But while I&#8217;m debugging the code that actually does the manipulation, I find myself stuck doing stupid stuff like:
</p>
<p><pre>
(gdb) p/x ((char*)[imageData bytes])[14]
$1 = 0x28
</pre>
</p>
<p>
Ugh! That&#8217;s no way to win the software wars. It occurred to me today that what I really want is something like Hex Fiend built right into the debugger. Why shouldn&#8217;t I be able to hex-dump my NSData objects directly from the console? It turns out I wasn&#8217;t alone in this wish, because Dan Wood <a href="http://gigliwood.com/weblog/Cocoa/Better_description_.html">recently published</a> a category on NSData that allows just that.
</p>
<p>
By simply compiling the NSData category into a given application, you give NSData&#8217;s debugging description superpowers. For instance, here&#8217;s me at the gdb console, examining the contents of the favicon.ico response I just received from NSURLConnection:</p>
<pre style="font-size:1em;">
<code>
(gdb) po imageData
NSData 350 bytes:
00 00 01 00 01 00 10 10 10 00 00 00 00 00 28 01 | ..............(.
00 00 16 00 00 00 28 00 00 00 10 00 00 00 20 00 | ......(....... .
00 00 01 00 04 00 00 00 00 00 C0 00 00 00 00 00 | ................
00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF | ................
FF 00 00 00 FF 00 00 00 EF 00 00 00 DE 00 00 00 | ................
CE 00 00 00 BD 00 00 00 AD 00 00 00 9C 00 00 00 | ................
8C 00 00 00 7B 00 00 00 52 00 00 00 42 00 00 00 | ....{...R...B...
29 00 00 00 10 00 00 00 00 00 00 00 00 00 11 11 | )...............
11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 | ................
11 11 11 11 11 11 13 31 11 11 12 55 21 11 1B B1 | .......1...U!...
13 D8 7F FF FB 31 1B B1 6F D4 FB 65 9F D2 1B DB | ....1..o..e....
FB 21 84 11 15 F5 1B FF FC 41 12 78 8D D1 1B B1 | .!.......A.x....
3C C1 2D FF FB 51 1B B1 1A D1 5F 71 11 11 1B C5 | < .-..Q...._q....
BF 81 1C C7 58 61 1A FF C6 11 12 BF FF 81 12 54 | ....Xa.........T
11 11 11 13 52 11 11 11 11 11 11 11 11 11 11 11 | ....R...........
11 11 11 11 11 11 11 11 11 11 11 11 11 11 00 00 | ................
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00 00 00 00 00 00 00 00 00 00 00 00 00 00       | ..............
Current language:  auto; currently objective-c
(gdb)
</code>
</code></pre>
</p>
<p>
Dan&#8217;s code is pretty much perfect as-is, but I couldn&#8217;t resist tacking on some additional features. His category hardcodes the dumped data to 1024 bytes, but in my case there are times when I&#8217;m interested in seeing more. I added two category methods to the mix:
</p>
<p><pre style="font-size:1em;">
<code>
// startOffset may be negative, indicating offset from end of data
- (NSString *)descriptionFromOffset:(int)startOffset;
- (NSString *)descriptionFromOffset:(int)startOffset
				limitingToByteCount:(unsigned int)maxBytes;
</code>
</pre>
</p>
<p>
Now I can peek at a specific subrange, or expand the default limit of 1024 bytes. I can even peek at the end of a chunk of data, by specifying a negative offset:
</p>
<p><pre style="font-size:1em;">
<code>
(gdb) po [mDocumentData descriptionFromOffset:-11]
NSData 109 bytes (showing bytes 98 through 109):
02 43 41 54 41 54 4F 4E 49 43 00                | .CATATONIC.
(gdb)
</code>
</pre>
</p>
<p>
Wow! This is a pretty huge addition to my debugging and development toolbelt. Many thanks to Dan Wood for providing the ready-made code to speed up my implementation.
</p>
<p>
<a href="http://www.red-sweater.com/blog/downloads/NSData+RSHexDump.zip">NSData+RSHexDump</a> is freely available to you, under an MIT license.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.red-sweater.com/blog/279/hexy-little-thing/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Xcode Pasteboard Accumulator</title>
		<link>http://www.red-sweater.com/blog/269/xcode-pasteboard-accumulator</link>
		<comments>http://www.red-sweater.com/blog/269/xcode-pasteboard-accumulator#comments</comments>
		<pubDate>Thu, 01 Feb 2007 23:17:04 +0000</pubDate>
		<dc:creator>Daniel Jalkut</dc:creator>
				<category><![CDATA[Carbon]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Usability]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://www.red-sweater.com/blog/269/xcode-pasteboard-accumulator</guid>
		<description><![CDATA[Way back in the MPW days, I used to rely heavily on an extension for the IDE that put powerful pasteboard manipulation tools in the window header. Essentially these tools let you treat your pasteboard like a stack, so you could easily accumulate multiple copies and then paste them all out at once. For some [...]]]></description>
			<content:encoded><![CDATA[<p>Way back in the <a href="http://developer.apple.com/tools/mpw-tools/">MPW</a> days, I used to rely heavily on an extension for the IDE that put powerful pasteboard manipulation tools in the window header. Essentially these tools let you treat your pasteboard like a stack, so you could easily accumulate multiple copies and then paste them all out at once.</p>
<p>
For some dumb reason, I&#8217;ve been living without such conveniences for several years now. I know there are many 3rd party products that add an epic amount of functionality to the standard copy and paste of the system, but I&#8217;m not really interested in running a separate application for this purpose.
</p>
<p>
It occurred to me that this would be a perfect use of Xcode&#8217;s <a href="http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeUserGuide/Contents/Resources/en.lproj/07_03_custom_scripts/chapter_48_section_4.html">Menu Scripts</a>. Xcode not only supports the addition of custom scripts to the menu bar, but supports a unique format by which the scripts can advertise keyboard shortcuts, and integrate seamlessly with Xcode&#8217;s text editor. For instance, you can use a script to process the selected text in Xcode and spit back out something else in its place.
</p>
<p>
<a href="http://www.red-sweater.com/blog/downloads/AppendToPasteBoard.zip">Append To Pasteboard</a> is a simple python script that takes advantage of the &#8220;pbcopy&#8221; and &#8220;pbpaste&#8221; commands to tack whatever you&#8217;ve selected in Xcode on to the end of the existing pasteboard. You stick this within your (horribly located) user scripts folder, where you must name the folders and files with numeric prefixes to inform Xcode where they belong. For example, the script lives in my home directory:
</p>
<p><pre>
/Users/daniel/Library/Application Support/
	Apple/Developer Tools/Scripts/
	10-User Scripts/1-DCJ/
</pre>
</p>
<p>
Unfortunately Xcode doesn&#8217;t handle the situation where some scripts come from your home directory, and some come from the /Library installation directory. So I put everything in my home directory. The &#8220;10-User Scripts&#8221; is how I tell it to name the menu bar item &#8220;User Scripts.&#8221; The &#8220;1-DCJ&#8221; folder is the folder with all my custom scripts in it, and since it is &#8220;1,&#8221; it comes before all of Apple&#8217;s standard scripts that I copied in (10-Open, 20-Search, etc). The process of providing scripts to Xcode is ugly but when you finally get it all put together, this is what you end up with:
</p>
<p>
<img src="http://www.red-sweater.com/blog/images/AppendToPasteboard.png"/>
</p>
<p>
Now it&#8217;s a snap to cruise through a .m and accumulate method declarations, for pasting into a corresponding .h. Note that the script always appends a newline to the existing pasteboard, which could be annoying depending on what you want to use it for. Since I envision myself almost always double-clicking a function or method declaration and appending it to a list, I find this behavior to be most convenient.
</p>
</p>
<p>Thanks to <a href="http://www.toxicsoftware.com/">Jon Wight</a> for helping with Python.</p>
<p>
<strong>Update:</strong> Any productivity gained by using this macro was certainly lost as I tried desperately to debug Xcode&#8217;s latest propensity to &#8220;beachball&#8221; on launch. Finally, I attached with gdb and found a telling backtrace. Hmm? Yep, when I &#8220;zipped&#8221; the script for upload to the blog, I left a zipped copy in the scripts folder. Next time I launched Xcode, it choked big time on trying to treat that zip file as a script.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.red-sweater.com/blog/269/xcode-pasteboard-accumulator/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>

