<?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>Vincent Gable's Blog &#187; Sample Code</title>
	<atom:link href="http://vgable.com/blog/category/sample-code/feed/" rel="self" type="application/rss+xml" />
	<link>http://vgable.com/blog</link>
	<description>my weblog.</description>
	<lastBuildDate>Tue, 29 Nov 2011 22:20:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>The Most Useful Objective-C Code I&#8217;ve Ever Written</title>
		<link>http://vgable.com/blog/2010/08/19/the-most-useful-objective-c-code-ive-ever-written/</link>
		<comments>http://vgable.com/blog/2010/08/19/the-most-useful-objective-c-code-ive-ever-written/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 10:01:01 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Announcement]]></category>
		<category><![CDATA[Bug Bite]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Research]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[LOG_EXPR]]></category>
		<category><![CDATA[macros]]></category>
		<category><![CDATA[NSLog]]></category>
		<category><![CDATA[Preprocessor]]></category>
		<category><![CDATA[printf]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=670</guid>
		<description><![CDATA[Actually, it&#8217;s the most useful code I&#8217;ve extended; credit for the core idea goes to Dave Dribin with his Handy NSString Conversion Macro. LOG_EXPR(x) is a macro that prints out x, no matter what type x is, without having to worry about format-strings (and related crashes from eg. printing a C-string the same way as [...]]]></description>
			<content:encoded><![CDATA[<p>Actually, it&#8217;s the most useful code I&#8217;ve <em>extended</em>; credit for the core idea goes to <a href="http://www.dribin.org/dave/">Dave Dribin</a> with his <a href="http://www.dribin.org/dave/blog/archives/2008/09/22/convert_to_nsstring/"><cite>Handy NSString Conversion Macro</cite></a>.</p>
<p><strong><code><a href="">LOG_EXPR</a>(x)</code> is a macro that prints out <code>x</code>, no matter what type <code>x</code> is</strong>, without having to worry about format-strings (and related crashes from eg. printing a C-string the same way as an <code>NSString</code>). It works on Mac OS X and iOS. Here are some examples,</p>
<p><code>LOG_EXPR(self.window.screen);</code></p>
<blockquote><p>self.window.screen = &lt;UIScreen: 0x6d20780; bounds = {{0, 0}, {320, 480}}; mode = &lt;UIScreenMode: 0x6d20c50; size = 320.000000 x 480.000000&gt;&gt;
</p></blockquote>
<p><code>LOG_EXPR(self.tabBarController.viewControllers);</code></p>
<blockquote><p>self.tabBarController.viewControllers = (<br />
    &#8220;&lt;UINavigationController: 0xcd02e00&gt;&#8221;,<br />
    &#8220;&lt;SavingsViewController: 0xcd05c40&gt;&#8221;,<br />
    &#8220;&lt;SettingsViewController: 0xcd05e90&gt;&#8221;<br />
)</p></blockquote>
<p>Pretty straightforward, really. The biggest convenience so far is having the expression printed out, so you don&#8217;t have to write out a name redundantly in the format string (eg. <code> NSLog(@"actionURL = %@", actionURL)</code>). But <code>LOG_EXPR</code> really shows it&#8217;s worth when you start using scalar or <code>struct</code> expressions:</p>
<p><code>LOG_EXPR(self.window.windowLevel);</code></p>
<blockquote><p>self.window.windowLevel = 0.000000</p></blockquote>
<p><code>LOG_EXPR(self.window.frame.size);</code></p>
<blockquote><p>self.window.frame.size = {320, 480}</p></blockquote>
<p>Yes, there are expressions that won&#8217;t work, but they&#8217;re pretty rare for me. I use <code>LOG_EXPR</code> every day. Several times. It&#8217;s not quite as good as having <a href="http://vgable.com/blog/2010/06/14/ask-f-script/">a REPL for Cocoa</a>, but it&#8217;s handy.</p>
<p><a href="#Get_LOG_EXPR">Give it a try</a>.</p>
<h3>How It Works</h3>
<p>The problem is how to pick a function or format string to print <code>x</code>, based on the type of <code>x</code>. C++&#8217;s type-based dispatch would be a good fit here, but it&#8217;s verbose (a full function-definition per type) and I wanted to use pure Objective-C if possible. Fortunately, <strong>Objective-C has an <a href="http://developer.apple.com/mac/library/documentation/cocoa/conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html"><code>@encode()</code></a>  compiler directive that returns a string describing any type it&#8217;s given.</strong> Unfortunately it works on <em>types</em>, not variables, but with C99 <strong>the <code><a href="http://gcc.gnu.org/onlinedocs/gcc/Typeof.html">typeof()</a></code> compiler directive lets us get the type of any variable</strong>, which we can pass to <code>@encode()</code>.  The final bit of compiler magic is using <a href="http://gcc.gnu.org/onlinedocs/cpp/Stringification.html">stringification (<code>#</code>)</a> to print out the literal string inside <code>LOG_EXPR()</code>&#8216;s parenthesis.</p>
<h3>The Macro, Line By Line</h3>
<div class="code-box">
<pre>
1 #define LOG_EXPR(_X_) do{\
2 	__typeof__(_X_) _Y_ = (_X_);\
3 	const char * _TYPE_CODE_ = @encode(__typeof__(_X_));\
4 	NSString *_STR_ = VTPG_DDToStringFromTypeAndValue(_TYPE_CODE_, &#038;_Y_);\
5 	if(_STR_)\
6 		NSLog(@"%s = %@", #_X_, _STR_);\
7 	else\
8 		NSLog(@"Unknown _TYPE_CODE_: %s for expression %s in function %s, file %s, line %d", _TYPE_CODE_, #_X_, __func__, __FILE__, __LINE__);\
9 }while(0)
</pre>
</div>
<ol>
<li>The first and last lines are a way to put <code>{}</code>&#8216;s around the macro to prevent <a href="http://en.wikipedia.org/wiki/C_preprocessor#Multiple_statements">unintended effects</a>. The <code>do{}while(0);</code> &#8220;loop&#8221; does nothing else.</li>
<li>First evaluate the expression, <code>_X_</code>, given to <code>LOG_EXPR</code> <em>once</em>, and store the result in a <code>_Y_</code>. We need to use <code><a href="http://gcc.gnu.org/onlinedocs/gcc/Typeof.html">typeof()</a></code> (which had to be written <code>__typeof__()</code> to appease some versions of GCC) to figure out the type of <code>_Y_</code>.</li>
<li><code>_TYPE_CODE_</code> is c-string that <a href="http://developer.apple.com/mac/library/documentation/cocoa/conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html">describes the type</a> of the expression we want to print out.</li>
<li>Now we have enough information to call a function, <code>VTPG_DDToStringFromTypeAndValue()</code> to convert the expression&#8217;s value to a string. We pass it the <code>_TYPE_CODE_</code> string, and <em>the address of </em> <code>_Y_</code>, which is a pointer, and has a known size. We can&#8217;t pass <code>_Y_</code> directly, because depending on what <code>_X_</code> is, it will have different types and could be of any size.</li>
<li><code>VTPG_DDToStringFromTypeAndValue()</code> returns <code>nil</code> if it can&#8217;t figure out how to convert a value to a string.</li>
<li>Everything went well, print the <a href="http://gcc.gnu.org/onlinedocs/cpp/Stringification.html">stringified</a> expression, <code>#_X_</code>, and  the string representing it&#8217;s value, <code>_STR_</code>.</li>
<li>otherwise…</li>
<li>The expression had a type we can&#8217;t handle, print out a verbose diagnostic message.</li>
<li>See line 1.</li>
</ol>
<h3>The <code>VTPG_DDToStringFromTypeAndValue()</code> Function</h3>
<p>See the source in <a href="http://github.com/VTPG/CommonCode/blob/master/VTPG_Common.m">VTPG_Common.m</a>:</p>
<p><iframe src ="http://github.com/VTPG/CommonCode/blob/master/VTPG_Common.m" width="100%" height="300">(Your browser does not support iframes.)</iframe></p>
<p>It&#8217;s derived from  <a href="http://www.dribin.org/dave/">Dave Dribin</a>&#8216;s function <a href="http://www.dribin.org/dave/blog/archives/2008/09/22/convert_to_nsstring/"> <code>DDToStringFromTypeAndValue()</code></a>, and is pretty straightforward: <code>strcmp()</code> the type-string, and if it matches a known type call a function, or use <code>+[NSString stringWithFormat]:</code>, to turn the value into a string.</p>
<h3>The First Step Twords Fixing Your Macro Problem is Admitting it&#8230;</h3>
<p>So yeah, maybe I went a little wild with macros here…</p>
<p>But it took out some <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">WET</a>-ness of the original code, and prevents me from accidentally mixing up types in a long wall of <code>if</code>s, eg.</p>
<div class="code-box">
<pre>
else if (strcmp(typeCode, @encode(NSRect)) == 0)
{
    return NSStringFromRect(*(NSRange *)value);
}
else if (strcmp(typeCode, @encode(NSRange)) == 0)
{
    return NSStringFromRect(*(NSRange *)value);
}
</pre>
</div>
<p>If I were cool, I&#8217;d use <code>NSDictionary</code>s to map from the <code>@encode</code>-string to an appropriate format string or function pointer.  This is conceptually cleaner; less error-prone than using macros; and almost certainly faster. Unfortunately, it gets a little tricky with functions, since I need to deference <code>value</code> into the proper type.</p>
<p>One final note from my testing, I could do away with the <code>strcmp()</code>s, because directly comparing <code>@encode</code> string pointers (eg <code>if(typeCode == @encode(NSString*))</code> works. I don&#8217;t know if it will <em>always</em> work though, so relying on it strikes me as a profoundly Bad Idea. But maybe that bad idea will give someone a good idea.</p>
<h3>Limitations</h3>
<h4>Arrays</h4>
<p>C arrays generally muck things up. Casting to a pointer works around this:</p>
<div class="code-box">
<pre>
char x[14] = "Hello, world!";
//LOG_EXPR(x); //error: invalid initializer
LOG_EXPR((char*)x); //prints fine
</pre>
</div>
<h4><code>__func__</code></h4>
<p>Because it is a <code>static const char []</code>, <code><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1642.html">__func__</a></code> (and <code>__FUNCTION__</code> or <code>__PRETTY_FUNCTION__</code>) need casting to <code>char*</code> to work with <code>LOG_EXPR</code>. Because logging out a function/method call is something I do frequently, I use the macro:</p>
<div class="code-box">
<pre>
#define LOG_FUNCTION()	NSLog(@"%s", __func__)</pre>
</div>
<h4><code>long double</code> (Leopard and older)</h4>
<p>On older systems, <code>LOG_EXPR</code> won&#8217;t work with a <code>long double</code> value, because <code>@encode(long double)</code> gives the same result as <code>@encode(double)</code>. This is a <a href="http://openradar.appspot.com/6468314">known issue</a> with the runtime. The top-level <code>LOG_EXPR</code> macro could detect a <code>long double</code> with <code>if((sizeof(_X_) == sizeof(long double)) &#038;&#038; (_TYPE_CODE_ == @encode(double)))</code>. But I doubt this will ever be necessary.</p>
<p>I haven&#8217;t actually written any code that uses <code>long double</code>, because I <strong>use <code><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/doc/uid/20000055-BCIHCEFJ">NSDecimal</a></code>, or another base-10 number format, for situations that require more precision than a <code>double</code>.</strong></p>
<h3>Scaling and Frameworks </h3>
<p>Growing <code>LOG_EXPR</code> to handle <em>every</em> type is a lot of work. I&#8217;ve only added types that I&#8217;ve actually needed to print. This has kept the code manageable, and seems to be working so far.</p>
<p>The biggest problem I have is <strong>how to deal with types that are in frameworks that not every project includes</strong>. Projects that use CoreLocation.framework need to be able to use <code>LOG_EXPR</code> to print out CoreLocation specific <code>struct</code>s, like <code> CLLocationCoordinate2D</code>. But projects that <em>don&#8217;t</em> use CoreLocation.framework don&#8217;t have a definition of the <code>CLLocationCoordinate2D</code> type, so code to convert it to a string won&#8217;t compile. There are two ways I&#8217;ve tried to solve the problem</p>
<h4>Comment-out framework-specific code</h4>
<p>This is pretty self-explanatory, I&#8217;ll fork VTPG_Common.m and un-comment-out code for types that my project needs to print. It works, but it&#8217;s drudgery. Programmers hate that.</p>
<h4>Hardcode type info</h4>
<p>The idea is to hard-code the string that <code>@encode(SomeType)</code> would evaluate to, and then (since we know how <code>SomeType</code> is laid out in memory) use casting and pointer-arithmetic to get at the fields.</p>
<p>For example:</p>
<div class="code-box">
<pre>
//This is a hack to print out CLLocationCoordinate2D, without needing to #import &lt;CoreLocation/CoreLocation.h&gt;
//A CLLocationCoordinate2D is a struct made up of 2 doubles.
//We detect it by hard-coding the result of @encode(CLLocationCoordinate2D).
//We get at the fields by treating it like an array of doubles, which it is identical to in memory.
if(strcmp(typeCode, "{?=dd}")==0)//@encode(CLLocationCoordinate2D)
	return [NSString stringWithFormat:@"{latitude=%g,longitude=%g}",((double*)value)[0],((double*)value)[1]];
</pre>
</div>
<p>This Just Works in a project that includes CoreLocation, and doesn&#8217;t mess up projects that don&#8217;t. Unfortunately it&#8217;s <em>horribly brittle</em>. Any Xcode or system update could break it. It&#8217;s not a tenable fix.</p>
<h3>Areas for Improvement</h3>
<p>If there&#8217;s some type <code>LOG_EXPR</code> can&#8217;t handle that you need, please <a href="http://github.com/VTPG/CommonCode">jump right in and improve it</a>!</p>
<p>When I have time, I plan to write a general parser for <code>@encode()</code>-strings. This will let me print out <em>any</em> <code>struct</code>, which mostly solves the type-defined-in-missing-framework problem, and would let <code>LOG_EXPR</code> Just Work with types from all kinds of POSIX/C libraries.</p>
<h3><a name="Get_LOG_EXPR"></a>Using <code>LOG_EXPR()</code> in Your Project </h3>
<p>Download <a href="http://github.com/VTPG/CommonCode/blob/master/VTPG_Common.m">VTPG_Common.m</a> and <a href="http://github.com/VTPG/CommonCode/blob/master/VTPG_Common.h">VTPG_Common.h</a> from <a href="http://github.com/VTPG/CommonCode">my github repository</a>, and add them to your Xcode project.</p>
<p>Now just add the line <code>#import "VTPG_Common.h"</code> to your prefix file (named <code>&lt;ProjectName&gt;_Prefix.pch</code> by default), after the <code>#ifdef __OBJC__</code>, for example:</p>
<div class="code-box">
<pre>
#ifdef __OBJC__
    #import &lt;Foundation/Foundation.h&gt;
    // maybe other files, depending on project  template...
    #import "VTPG_Common.h"
#endif</pre>
</div>
<p>Now <code>LOG_EXPR()</code> will work everywhere in your project.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/08/19/the-most-useful-objective-c-code-ive-ever-written/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>My UIViewController Template</title>
		<link>http://vgable.com/blog/2010/08/15/my-uiviewcontroller-template/</link>
		<comments>http://vgable.com/blog/2010/08/15/my-uiviewcontroller-template/#comments</comments>
		<pubDate>Mon, 16 Aug 2010 03:09:40 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Template]]></category>
		<category><![CDATA[UIViewController]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=666</guid>
		<description><![CDATA[I haven&#8217;t formalized this as a proper Xcode template, but this is what&#8217;s in my PrototypeViewController.m file that I copy/paste over the UIViewController subclasses Xcode makes. @interface MyViewController () @end @implementation MyViewController - (void) releaseViewObjects; { if([[self superclass] instancesRespondToSelector:@selector(releaseViewObjects)]) [(id)super releaseViewObjects]; } - (void)viewDidUnload; { [super viewDidUnload]; [self releaseViewObjects]; } - (void)dealloc; { [self releaseViewObjects]; [...]]]></description>
			<content:encoded><![CDATA[<p>I haven&#8217;t formalized this as a proper Xcode template, but this is what&#8217;s in my <code>PrototypeViewController.m</code> file that I copy/paste over the <code>UIViewController</code> subclasses Xcode makes.</p>
<div class="code-box">
<pre>

@interface MyViewController ()
@end

@implementation MyViewController
- (void) releaseViewObjects;
{
	if([[self superclass] instancesRespondToSelector:@selector(releaseViewObjects)])
		[(id)super releaseViewObjects];
}

- (void)viewDidUnload;
{
    [super viewDidUnload];
    [self releaseViewObjects];
}

- (void)dealloc;
{
    [self releaseViewObjects];
    [super dealloc];
}

@end
</pre>
</div>
<p>Here are the reasons why, in no particular order:</p>
<h3>Commented-Out Code is Evil</h3>
<p>Littering source code with &#8220;comments&#8221; full of crufty, obsolete, or unimplemented code is not a good thing. <strong>Xcode&#8217;s default template is full of commented-out code</strong>. If you&#8217;re totally new to the platform, starting from the templates aren&#8217;t a bad way to learn.  But in my experiance, they do harm to a production code-base, by injecting hundreds of lines of commented-out code into a project.</p>
<h3>Share code between <code>viewDidUnload</code> and <code>dealloc</code> With <code> releaseViewObjects </code></h3>
<p>In my world, <code>releaseViewObjects</code> is <strong>solely responsible</strong> for cleaning up every <code>IBOutlet</code>, and any objects created in <code>viewDidLoad</code>.</p>
<p>There are technical reasons why this is a little scary. Calling a method in <code>dealloc</code> is potentially risky, because the object may be in an invalid half-torn-down state, and because <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html">Dark Runtime Magicks</a> could be afoot (see <a href="http://www.mikeash.com/pyblog/friday-qa-2009-11-27-using-accessors-in-init-and-dealloc.html"><cite>Using Accessors in Init and Dealloc</cite></a>.)</p>
<p>But in my experience, such bugs, although as scary as they sound, are rare corner-cases and still quite fixable. But <em>every</em> <code>UIViewController</code> needs to clean up after itself, so simplifying the universally common case is a net win.</p>
<p>The <code>if([[self superclass] instancesRespondToSelector:@selector(releaseViewObjects)])</code> test wouldn&#8217;t be necessary if I added another class between <code>UIViewController</code> and my real code, so that I was sure my class&#8217; <code>super</code> implemented <code>releaseViewObjects</code>. But adding a subclass just to implement one empty method, to avoid a two-line test, isn&#8217;t worth it.</p>
<p>The <code>(id)super</code> cast is intentional, to prevent compiler warnings.</p>
<p>I have to use the more complex <code>[[self superclass] instancesRespondToSelector:</code> test, because <code>-[super respondsToSelector:]</code> <a href="http://www.cocoabuilder.com/archive/cocoa/208788-super-respondstoselector.html">doesn&#8217;t work</a>.</p>
<h3>I Won&#8217;t <em>Really</em> Get To <code>didReceiveMemoryWarning</code></h3>
<p>I&#8217;m not proud to admit this, but it&#8217;s true. We&#8217;ve all been told that a good iPhone program <em>must</em> release resources when it gets a memory warning, or else it will be killed. But in practice, there have always been better places to spend my time (or at least it sure feels that way!) Spending a few hours in Instruments to fix leaks prevents memory warnings in the first place, and that&#8217;s a bigger win.</p>
<p>Besides, <strong>80% of what <code>didReceiveMemoryWarning</code> would do is handled in <code> releaseViewObjects</code></strong>, which is automatically called by the default implementation.</p>
<p>So I break with Xcode and leave <code>didReceiveMemoryWarning</code> out of my template, because <em>the default class won&#8217;t use it</em>.</p>
<h3>What About <code>init</code>?</h3>
<p>I don&#8217;t have a default <code>init(With…)</code> method. <strong>I try to use <code>autorelease</code>-ed objects everywhere I can</strong>, so I&#8217;m more comfortable implementing <code>+[MyViewController viewControllerForFoo:]</code>.</p>
<p>But I don&#8217;t have a default constructor of <em>any</em> kind, because <strong>a constructor should take every value it <em>needs</em></strong>, and I don&#8217;t know what these values are until I&#8217;ve written a bit more of the class. It&#8217;s a chicken and egg problem.</p>
<p>Once I&#8217;ve written out a bit more of the class, I&#8217;ll usually build something that looks like:</p>
<div class="code-box">
<pre>
+ (RouteMapViewController*) routeMapViewControllerWithWaypoints:(NSArray*)waypoints mapRegion:(MKCoordinateRegion)region;
{
	RouteMapViewController *vc = [[[self class] new] autorelease];
	vc.title = NSLocalizedString(@"The Path",@"");
	vc.hidesBottomBarWhenPushed = YES;
	vc.waypoints = waypoints;
	vc.mapRegion = region;
	return vc;
}
</pre>
</div>
<p>For what it&#8217;s worth I <a href="http://weblog.bignerdranch.com/?p=56">use this pattern to implement a 0-argument <code>-init</code></a>.</p>
<h3>Empty Class Extension</h3>
<p><a href="http://www.friday.com/bbum/2009/09/11/class-extensions-explained/">Class extensions</a> are the best way to have &#8220;private&#8221; things in Objective-C. They let the compiler catch objects using another object&#8217;s private methods. They let a class have publicly <code>readonly</code>, but internally <code>readwrite</code>, properties.</p>
<p>Bottom line: every nontrivial object I&#8217;ve written uses them, so they&#8217;re in my template.</p>
<h3>Nothing Else (For Now)</h3>
<p>My template is smaller than Xcode&#8217;s. That is by design. Outside of <a href="http://js1k.com/">esoteric contests</a>, having less code to maintain is a good thing. So <strong>I prefer a template that tries very hard to avoid adding code I don&#8217;t need.</strong></p>
<p>Do you disagree with any of my choices? Please <strong>leave a comment explaining why</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/08/15/my-uiviewcontroller-template/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hack: Counting Variadic Arguments in C</title>
		<link>http://vgable.com/blog/2009/10/16/hack-counting-varadic-arguments-in-c/</link>
		<comments>http://vgable.com/blog/2009/10/16/hack-counting-varadic-arguments-in-c/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 05:04:09 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Research]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[Usability]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Introspection]]></category>
		<category><![CDATA[Parsing]]></category>
		<category><![CDATA[Programming Language Design]]></category>
		<category><![CDATA[Variadic Functions]]></category>
		<category><![CDATA[Variadic Macros]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=442</guid>
		<description><![CDATA[This isn&#8217;t practical, but I think it&#8217;s neat that it&#8217;s doable in C99. The implementation I present here is incomplete and for illustrative purposes only. Background C&#8217;s implementation of variadic functions (functions that take a variable-number of arguments) is characteristically bare-bones. Even though the compiler knows the number, and type, of all arguments passed to [...]]]></description>
			<content:encoded><![CDATA[<p>This isn&#8217;t practical, but I think it&#8217;s neat that it&#8217;s doable in C99. The implementation I present here is <strong>incomplete and for illustrative purposes only</strong>.</p>
<h3>Background</h3>
<p>C&#8217;s implementation of <a href="http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html">variadic functions</a> (functions that take a variable-number of arguments) is characteristically bare-bones. Even though the compiler knows the number, and type, of all arguments  passed to variadic functions; there isn&#8217;t a mechanism for the function to get this information from the compiler. Instead, programmers need to pass an extra argument, like the <code>printf</code> <a href="http://en.wikipedia.org/wiki/Printf#printf_format_placeholders">format-string</a>, to tell the function &#8220;these are the arguments I gave you&#8221;. This has worked for over 37 years. But it&#8217;s clunky &#8212; you have to write the same information twice, once for the compiler and again to tell the function what you told the compiler.</p>
<h3>Inspecting Arguments in C</h3>
<h4>Argument Type</h4>
<p><strong>I don&#8217;t know of a way to find the type of the Nth argument to a varadic function, called with heterogeneous types.</strong> If you can figure out a way, I&#8217;d love to know. <strong>The <a href="http://gcc.gnu.org/onlinedocs/gcc/Typeof.html"><code>typeof</code></a> extension is often sufficient to write generic code that works when every argument has the same type.</strong> (<a href="http://www.cplusplus.com/doc/tutorial/templates/">C++ templates</a> also solve this problem if we step outside of C-proper.)</p>
<h4>Argument Count (The Good Stuff Starts Here)</h4>
<p><strong>By using <a href="http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html">variadic macros</a>, and <a href="http://gcc.gnu.org/onlinedocs/cpp/Stringification.html">stringification (<code>#</code>)</a>, we can actually pass a function the literal string of its argument list from the source code &#8212; which it can parse to determine how many arguments it was given.<br />
</strong></p>
<p>For example, say <code>f()</code> is a variadic function. We create a variadic wrapper macro, <code>F()</code> and call it like so in our source code,</p>
<pre>x = F(a,b,c);</pre>
<p>The preprocessor expands this to,</p>
<pre>x = f("a,b,c",a,b,c)</pre>
<p>Or perhaps,</p>
<pre>x = f(count_arguments("a,b,c"),a,b,c)</pre>
<p>where <code>count_arguments(char *s)</code> returns the number of arguments in the string source-code string <code>s</code>. (Technically <code>s</code> would be an argument-expression-list).</p>
<h3>Example Code</h3>
<p>Here&#8217;s an implementation for, <code>iArray()</code>, an array-builder for <code>int</code> values, very much like <a href="http://www.amazon.com/gp/product/0596101996?ie=UTF8&#038;tag=vincgabl-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=0596101996">JavaScript</a>&#8216;s <code>Array()</code> constructor. Unlike the <a href="http://www.youtube.com/watch?v=hQVTIJBZook">quirky JavaScript</a> <code>Array()</code>, <code>iArray(3)</code> returns an array containing just the element 3, <code>[3]</code>, not an uninitilized array with 3 elements, <code>[undefined, undefined, undefined]</code>. Another difference: <code>iArray()</code>, invoked with no arguments, is invalid, and will not compile.</p>
<pre>
#define iArray(...) alloc_ints(count_arguments(#__VA_ARGS__), __VA_ARGS__)
</pre>
<p>This macro is pretty straightforward. It&#8217;s given a variable number of arguments, represented by <code>__VA_ARGS__</code> in the expansion. <code>#__VA_ARGS__</code> <a href="http://gcc.gnu.org/onlinedocs/cpp/Stringification.html">turns the code into a string</a> so that <code>count_arguments</code> can analyze it. (If you were doing this for real, you should use two levels of <a href="http://gcc.gnu.org/onlinedocs/cpp/Stringification.html">stringification</a> though, otherwise macros won&#8217;t be fully expanded. I choose to keep things &#8220;demo-simple&#8221; here.)</p>
<pre>
unsigned count_arguments(char *s){
	unsigned i,argc = 1;
		for(i = 0; s[i]; i++)
			if(s[i] == ',')
				argc++;
	return argc;
}
</pre>
<p>This is a <strong>dangerously naive</strong> implementation and only works correctly when <code>iArray()</code> is given a straightforward non-empty list of values or variables. Basically it&#8217;s the least code I could write to make a working demo.</p>
<p>Since <code>iArray</code> must have at least one argument to compile, we just count the commas in the argument-list to see how many other arguments were passed. Simple to code, but it fails for more complex expressions like <code>f(a,g(b,c))</code>.</p>
<pre>
int *alloc_ints(unsigned count, ...){
	unsigned i = 0;
	int *ints = malloc(sizeof(int) * count);
	va_list args;
    va_start(args, count);
	for(i = 0; i < count; i++)
		ints[i] = va_arg(args,int);
	va_end(args);
	return ints;
}
</pre>
<p>Just as you'd expect, this code allocates enough memory to hold <code>count</code> <code>int</code>s, and fills it with the remaining <code>count</code> arguments. Bad things happen if &lt; <code>count</code> arguments are passed, or they are the wrong type.</p>
<p><a href="http://vgable.com/code/iArray.c">Download the code</a>, if you like.</p>
<h3><a href="http://steve-yegge.blogspot.com/2007/06/rich-programmer-food.html">Parsing is Hard</a>, Let's Go Shopping</h3>
<p>I didn't even try to correctly parse <em>any</em> valid argument-expression-list in <code>count_arguments</code>. It's non trivial. I'd rather deal with choosing the correct <code>MAX3</code> or <code>MAX4</code> macro in a few places than maintain such a code base.</p>
<p>So this kind of introspection isn't really practical in C. But it's neat that it can be done, without any tinkering with the compiler or language.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2009/10/16/hack-counting-varadic-arguments-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Best Quicksort Ever</title>
		<link>http://vgable.com/blog/2009/05/31/the-best-quicksort-ever/</link>
		<comments>http://vgable.com/blog/2009/05/31/the-best-quicksort-ever/#comments</comments>
		<pubDate>Sun, 31 May 2009 06:59:02 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[College]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Quicksort]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/2009/05/31/the-best-quicksort-ever/</guid>
		<description><![CDATA[The first time I saw this quicksort in Haskell was an eye opening moment, qsort [] = [] qsort (x:xs) = qsort (filter (&#60; x) xs) ++ [x] ++ qsort (filter (&#62;= x) xs) The first line reads: &#8220;When you sort an empty list ([]), the result is another empty list&#8221;. The second line reads: [...]]]></description>
			<content:encoded><![CDATA[<p>The first time I saw <a href="http://www.haskell.org/haskellwiki/Introduction#Ease_of_understanding">this quicksort in Haskell</a> was an eye opening moment,</p>
<blockquote>
<pre>
qsort []     = []
qsort (x:xs) = qsort (filter (&lt; x) xs) ++ [x] ++ qsort (filter (&gt;= x) xs)
</pre>
<p>The first line reads: &#8220;When you sort an empty list (<code>[]</code>), the result is another empty list&#8221;. The second line reads: &#8220;To sort a list whose first element is named <code>x</code> and the rest of which is named <code>xs</code>, sort the elements of <code>xs</code> that are less than <code>x</code>, sort the elements of <code>xs</code> that are greater than or equal to <code>x</code>, and concatenate (<code>++</code>) the results, with <code>x</code> sandwiched in the middle.&#8221;
</p></blockquote>
<p>The code is so concise, yet clear (even with cryptic variable names like <code>xs</code>). The day my professor wrote it on the whiteboard was the first time I internalized that there might be something good about the <em>alien</em> world of functional programming.</p>
<p>The biggest revelation to me was, <code>filter (&lt; x) xs</code> . It&#8217;s amazing that <code>(&lt; x)</code> builds a temporary, unnamed, function equivalent to C++,</p>
<pre>bool lessThanX(AnyOrderedType y){
    return y &lt; X;
}
//plus the definition of X somewhere...</pre>
<p><em>Building a function!</em> It&#8217;s still profound stuff to me. And <strong>clearly it really uses fewer lines of code</strong>. Amazingly, using <a href="http://en.wikipedia.org/wiki/List_comprehension">list comprehension</a> syntax is not more concise,</p>
<pre>qsort (x:xs) = qsort [i | i &lt;- xs, i &lt; x] ++ [x] ++ qsort [i | i &lt;- xs, i &lt;= x]</pre>
<p>compared to the original,</p>
<pre>qsort (x:xs) = qsort (filter (&lt; x) xs) ++ [x] ++ qsort (filter (&gt;= x) xs)</pre>
<p>I hope this is an <em>ah-ah</em> moment for someone else too. I&#8217;d love to know what made you interested in functional programming; or if you know of a more elegant quicksort implementation.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2009/05/31/the-best-quicksort-ever/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Improving Twitter.com: Space to Work</title>
		<link>http://vgable.com/blog/2009/05/19/improving-twittercom-space-to-work/</link>
		<comments>http://vgable.com/blog/2009/05/19/improving-twittercom-space-to-work/#comments</comments>
		<pubDate>Tue, 19 May 2009 19:14:50 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Usability]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Safari]]></category>
		<category><![CDATA[Twitter]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[Writing]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/2009/05/19/improving-twittercom-space-to-work/</guid>
		<description><![CDATA[The Change Enlarge the &#8220;What are you doing&#8221; box on Twitter.com, to make compressing substantial ideas easier. Motivation I&#8217;ve been disappointed with the posting interface of every Twitter-client I&#8217;ve tried so far. Just like any writing, tweets start with a first draft. My first drafts are often longer than 140 characters. That shouldn&#8217;t be a [...]]]></description>
			<content:encoded><![CDATA[<h3>The Change</h3>
<p>Enlarge the &#8220;What are you doing&#8221; box on <a href="http://twitter.com">Twitter.com</a>, to make compressing substantial ideas easier.</p>
<p><img src="http://vgable.com/blog/wp-content/uploads/2009/05/picture-5.png" alt="Twitter.com with a larger text-field" border="0" width="539" height="182" align="center" /></p>
<h3>Motivation</h3>
<p>I&#8217;ve been disappointed with the posting interface of every Twitter-client I&#8217;ve tried so far. Just like any writing, tweets start with a first draft. My first drafts are often longer than 140 characters. That shouldn&#8217;t be a problem; trimming the fat is part of any editing process. But most <strong>Twitter-interfaces are so downright <em>hostile</em> to anything longer then 140 characters</strong> that trimming a 145 letter utterance is a frustrating study in fighting my tools.</p>
<p>(The worst client I tried was, <a href="http://www.drinkbrainjuice.com/products/trial/blogo" rel="nofollow" >Blogo</a>, which would <em>stop you from typing and yell at you with a dialog</em> if you dared press another key after typing 140 characters. But <a href="http://iconfactory.com/software/twitterrific" rel="nofollow" >Twitterrific</a> was little better; I don&#8217;t understand how something so user-<em>un</em>friendly became so popular.)</p>
<p>Even <a href="http://twitter.com">Twitter.com</a> doesn&#8217;t give you enough room for writing a long, but under-the-limit tweet. To see for yourself, just start typing &#8220;mmmmm&#8221;; the box will run out of room before you run out of characters.  It&#8217;s downright crazy to have to scroll to see all of a <em>tweet</em> you are writing.</p>
<p>Now there&#8217;s nothing wrong with trying to prescribe a pithy style of communication. Clearly Twitter wouldn&#8217;t have worked otherwise. But punishing users for doing the &#8220;wrong&#8221; thing isn&#8217;t as effective as <strong>giving them the tools to change their behavior</strong>, to wit: space to work on shortening their writing.</p>
<h3>The Code</h3>
<p>This <a href="http://www.w3schools.com/css/">CSS</a> code makes the direct-messaging, and &#8220;what are you doing?&#8221; text-boxes tall enough to hold 5 lines of text without scrolling. By default Twitter&#8217;s web interface only holds 2 lines of text on screen.</p>
<pre>
#dm_update_box #direct_message_form fieldset div.info textarea#text,
#status_update_box #status_update_form fieldset div.info textarea#status {
	height: 6em !important;
}
</pre>
<p>The selectors I used are pretty specific to <a href="http://twitter.com">Twitter.com</a>, so it&#8217;s unlikely this will interfere with another site&#8217;s layout, unless it&#8217;s HTML code is nearly identical to Twitter&#8217;s.</p>
<h3>How-To: Safari</h3>
<p>Copy the above code into a .css file, (&#8220;CustomSafari.css&#8221; is what I called mine) then select that file in <strong>Safari -> Preferences -> Advanced -> Style sheet:</strong><br />
<img src="http://vgable.com/blog/wp-content/uploads/2009/05/safaristylesheet.png" alt="safariStyleSheet.png" border="0" width="588" height="398" align="center" /></p>
<p>After restarting Safari, Twitter&#8217;s web interface should give you room to work.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2009/05/19/improving-twittercom-space-to-work/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Concise NSDictionary and NSArray Lookup</title>
		<link>http://vgable.com/blog/2009/05/15/concise-nsdictionary-and-nsarray-lookup/</link>
		<comments>http://vgable.com/blog/2009/05/15/concise-nsdictionary-and-nsarray-lookup/#comments</comments>
		<pubDate>Fri, 15 May 2009 19:13:02 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Research]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[Usability]]></category>
		<category><![CDATA[NSArray]]></category>
		<category><![CDATA[NSDictionary]]></category>
		<category><![CDATA[Programming Language Design]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/2009/05/15/concise-nsdictionary-and-nsarray-lookup/</guid>
		<description><![CDATA[I started writing a list of ways I thought Objective-C could be improved, and I realized that many of my wishes involved more compact syntax. For example [array objectAtIndex:1] is so verbose I think it diminishes readability, compared to array[1]. I can&#8217;t quite match that brevity (can you, by using Objective-C++?), but with a one-line [...]]]></description>
			<content:encoded><![CDATA[<p>I started writing a list of ways I thought Objective-C could be improved, and I realized that many of my wishes involved more compact syntax. For example <code>[array objectAtIndex:1]</code> is so verbose I think it diminishes readability, compared to <code>array[1]</code>.</p>
<p>I can&#8217;t quite match that brevity (can you, by using Objective-C++?), but with a one-line category, you can say, <code>x = [array:1];</code>.</p>
<pre>
@interface NSArray (ConciseLookup)
- (id):(NSUInteger)index;
@end
@implementation NSArray (ConciseLookup)
- (id):(NSUInteger)index;
{
	return [self objectAtIndex:index];
}
@end
</pre>
<p>My question is: <strong>do you find this compact &#8220;syntax&#8221; useful at all, or is it added complexity with no substantial code compression?</strong> Personally I think the latter, but the number of wishes I had involving  more concise Objective-C syntax makes me wonder&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2009/05/15/concise-nsdictionary-and-nsarray-lookup/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How To Check if an Application is Running With AppleScript</title>
		<link>http://vgable.com/blog/2009/04/24/how-to-check-if-an-application-is-running-with-applescript/</link>
		<comments>http://vgable.com/blog/2009/04/24/how-to-check-if-an-application-is-running-with-applescript/#comments</comments>
		<pubDate>Sat, 25 Apr 2009 00:46:39 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[Apple Script]]></category>
		<category><![CDATA[System Events]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/2009/04/24/how-to-check-if-an-application-is-running-with-applescript/</guid>
		<description><![CDATA[on ApplicationIsRunning(appName) tell application "System Events" to set appNameIsRunning to exists (processes where name is appName) return appNameIsRunning end ApplicationIsRunning Use it like, if ApplicationIsRunning("Mail") then display dialog "Don't forget to write mom!" end if On Mac OS X 10.5, this worked for me even when the application-file&#8217;s name was changed. On 10.4 I do [...]]]></description>
			<content:encoded><![CDATA[<pre>
on ApplicationIsRunning(appName)
	tell application "System Events" to set appNameIsRunning to exists (processes where name is appName)
	return appNameIsRunning
end ApplicationIsRunning
</pre>
<p>Use it like,</p>
<pre>if ApplicationIsRunning("Mail") then
	display dialog "Don't forget to write mom!"
end if</pre>
<p>On Mac OS X 10.5, this worked for me even when the application-file&#8217;s name was changed. On 10.4 I do not expect that it would still work if someone renamed the application, unless you used the <code><strong>creator type</strong></code> to locate the process, not the <code>name</code>.</p>
<p>You might also be interested in how to get the name of the frontmost application, here&#8217;s how:</p>
<pre>tell application "System Events" to set <strong>FrontAppName</strong> to name of first process where frontmost is true
if FrontAppName is "DVD Player" then
	display dialog "Get to work!"
end if
</pre>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2009/04/24/how-to-check-if-an-application-is-running-with-applescript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>-[NSURL isEqual:] Gotcha</title>
		<link>http://vgable.com/blog/2009/04/22/nsurl-isequal-gotcha/</link>
		<comments>http://vgable.com/blog/2009/04/22/nsurl-isequal-gotcha/#comments</comments>
		<pubDate>Thu, 23 Apr 2009 00:05:07 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Bug Bite]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[isEqual:]]></category>
		<category><![CDATA[NSArray]]></category>
		<category><![CDATA[NSDictionary]]></category>
		<category><![CDATA[NSSet]]></category>
		<category><![CDATA[NSString]]></category>
		<category><![CDATA[NSURL]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/2009/04/22/nsurl-isequal-gotcha/</guid>
		<description><![CDATA[BREAKING UPDATE: Actually comparing the -absoluteURL or -absoluteString of two NSURLs that represent a file is not good enough. One may start file:///, and the other file://localhost/, and they will not be isEqual:! A work around is to compare the path of each NSURL. I&#8217;m still looking into the issue, but for now I am [...]]]></description>
			<content:encoded><![CDATA[<p>BREAKING UPDATE: Actually comparing the <code>-absoluteURL</code> or <code>-absoluteString</code> of two <code>NSURL</code>s that represent a file is <em>not good enough</em>.  One may start <code>file:///</code>, and the other <code>file://localhost/</code>, and <em>they will not be <code>isEqual:</code></em>!  A work around is to compare the <code>path</code> of each <code>NSURL</code>. I&#8217;m still looking into the issue, but for now I am using the following method to compare <code>NSURL</code>s.</p>
<pre>@implementation NSURL (IsEqualTesting)
- (BOOL) isEqualToURL:(NSURL*)otherURL;
{
	return [[self absoluteURL] isEqual:[otherURL absoluteURL]] ||
	[self isFileURL] &#038;&#038; [otherURL isFileURL] &#038;&#038;
	([[self path] isEqual:[otherURL path]]);
}
@end
</pre>
<p><code>[a isEqual:b]</code> may report <code>NO</code> for two <code>NSURL</code>s that both resolve to the same resource (website, file, whatever). So <strong>compare <code>NSURL</code>s like <code>[[a absoluteString] isEqual:[b absoluteString]]</code></strong>. It&#8217;s important to be aware of this gotcha, because URLs are Apple&#8217;s preferred way to represent file paths, and APIs are starting to require them. <strong>Equality tests that worked for <code>NSString</code> file-paths may fail with <code>NSURL</code> file-paths.</strong></p>
<p><a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURL/isEqual:">The official documentation says</a></p>
<blockquote><p> two <code>NSURLs</code> are considered equal if they both have the same base <a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURL/baseURL"><code>baseURL</code></a> and <a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURL/relativeString"><code>relativeString</code></a>.</p></blockquote>
<p>Furthermore,</p>
<blockquote><p>An <code>NSURL</code> object is composed of two parts—a potentially nil base URL and a string that is resolved relative to the base URL. An <code>NSURL</code> object whose string is fully resolved without a base is considered absolute; all others are considered relative.
</p></blockquote>
<p>In other words, two <code>NSURL</code> objects can resolve to the same absolute URL, but have a different base URL, and be considered <code>!isEqual:</code>.</p>
<p>An example should make this all clear,</p>
<pre>
NSURL *VGableDotCom = [NSURL URLWithString:@"http://vgable.com"];
NSURL *a = [[NSURL alloc] initWithString:@"blog" relativeToURL:VGableDotCom];
NSURL *b = [[NSURL alloc] initWithString:@"http://vgable.com/blog" relativeToURL:nil];
<a href="http://vgable.com/blog/2008/08/05/simpler-logging-2/">LOG_INT</a>([a isEqual:b]);
<a href="http://vgable.com/blog/2008/08/05/simpler-logging-2/">LOG_INT</a>([[a absoluteURL] isEqual:[b absoluteURL]]);
<a href="http://vgable.com/blog/2008/08/05/simpler-logging-2/">LOG_ID</a>([a absoluteURL]);
<a href="http://vgable.com/blog/2008/08/05/simpler-logging-2/">LOG_ID</a>([b absoluteURL]);
</pre>
<blockquote><p>
[a isEqual:b] = 0<br />
[[a absoluteURL] isEqual:[b absoluteURL]] = 1<br />
[a absoluteURL] = http://vgable.com/blog<br />
[b absoluteURL] = http://vgable.com/blog
</p></blockquote>
<p>Remember that <strong>collections use <code>isEqual:</code> to determine equality, so you may have to convert an <code>NSURL</code> to an <code> absoluteURL</code> to get the behavior you expect, especially with <code>NSSet</code> and <code>NSDictionary</code>.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2009/04/22/nsurl-isequal-gotcha/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting the Current URL from a WebView</title>
		<link>http://vgable.com/blog/2009/04/22/getting-the-current-url-from-a-webview/</link>
		<comments>http://vgable.com/blog/2009/04/22/getting-the-current-url-from-a-webview/#comments</comments>
		<pubDate>Wed, 22 Apr 2009 18:52:41 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Multilingual]]></category>
		<category><![CDATA[UIWebView]]></category>
		<category><![CDATA[WebView]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/2009/04/22/getting-the-current-url-from-a-webview/</guid>
		<description><![CDATA[UPDATED 2009-04-30: WARNING: this method will not always give the correct result. +[NSURL URLWithString:] requires it&#8217;s argument to have unicode characters %-escaped UTF8. But stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding will convert # to %23, so http://example.com/index.html#s1 would become http://example.com/index.html%23s1. Unfortunately, the two URLs are not equivalent. The un-%-escaped one refers to section #s1 in the file index.html, and the [...]]]></description>
			<content:encoded><![CDATA[<p>UPDATED 2009-04-30: WARNING: <strong>this method will <em>not</em> always give the correct result.</strong><a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/clm/NSURL/URLWithString:"> <code>+[NSURL URLWithString:]</code> requires it&#8217;s argument to have unicode characters %-escaped UTF8</a>.  But <code>stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding</code> will convert <code>#</code> to <code>%23</code>, so <code>http://example.com/index.html#s1</code> would become <code>http://example.com/index.html%23s1</code>. Unfortunately, the two URLs are <em>not</em> equivalent. The un-%-escaped one refers to section <code>#s1</code> in the file <code>index.html</code>, and the other tries to fetch the file <code>index.html#s1</code> (&#8220;index dot html#s1&#8243;). I have not yet implemented a workaround, although I suspect one is possible, by building the <code>NSURL</code> out of bits of the <a href="http://www.comptechdoc.org/independent/web/cgi/javamanual/javalocation.html">JavaScript location object</a>, rather then trying to convert the whole string.</p>
<hr />
<p><code>UIWebView</code>/<code>WebView</code> does not provide a way to find the URL of the webpage it is showing. But there&#8217;s a simple (and neat) way to get it using embedded JavaScript.</p>
<p><a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/Reference/Reference.html#//apple_ref/occ/instm/UIWebView/stringByEvaluatingJavaScriptFromString:"><code> - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script</code></a></p>
<p>Is a deceptively powerful method that can execute dynamically constructed JavaScript, and lets you embed JavaScript snippets in Cocoa programs. We can use it to embed one line of JavaScript to ask a <code>UIWebView</code> for the URL it&#8217;s showing.</p>
<pre>@interface UIWebView (CurrentURLInfo)
- (NSURL*) locationURL;
@end
@implementation UIWebView (CurrentURLInfo)
- (NSURL*) locationURL;
{
	NSString *rawLocationString = [self stringByEvaluatingJavaScriptFromString:@"location.href;"];
	if(!rawLocationString)
		return nil;
	//URLWithString: needs percent escapes added or it will fail with, eg. a file:// URL with spaces or any URL with unicode.
	locationString = [locationString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	return [NSURL URLWithString:locationString]
}
@end</pre>
<p>With the <code> CurrentURLInfo </code> category, you can do <code>aWebView.locationURL</code> to get the URL of the page a <code>WebView</code> is showing.</p>
<p><small><br />
One last note, the </p>
<pre>if(!rawLocationString)
	return nil;</pre>
<p>special-case was only necessary, because  <a href="http://openradar.appspot.com/6810626"> <code>[NSURL URLWithString:nil]</code> throws an exception (rdar://6810626</a>). But Apple has decided that this is correct behavior.</small></p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2009/04/22/getting-the-current-url-from-a-webview/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Beware rangeOf NSString Operations</title>
		<link>http://vgable.com/blog/2009/04/19/beware-rangeof-nsstring-operations/</link>
		<comments>http://vgable.com/blog/2009/04/19/beware-rangeof-nsstring-operations/#comments</comments>
		<pubDate>Sun, 19 Apr 2009 15:42:05 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Bug Bite]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[NSRange]]></category>
		<category><![CDATA[NSString]]></category>
		<category><![CDATA[Objective-C 2.0]]></category>
		<category><![CDATA[x86]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/2009/04/19/beware-rangeof-nsstring-operations/</guid>
		<description><![CDATA[I have repeatedly had trouble with the rageOf&#8230; NSString methods, because they return a struct. Going forward I will do more to avoid them, here are some ways I plan to do it. Sending a message that returns a struct to nil can &#8220;return&#8221; undefined values. With small structs like NSRange, you are more likely [...]]]></description>
			<content:encoded><![CDATA[<p>I have repeatedly had trouble with the <a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/rangeOfCharacterFromSet:"><code>rageOf</code>&#8230; <code>NSString</code> methods</a>, because they return a <code>struct</code>. Going forward I will do more to avoid them, here are some ways I plan to do it.</p>
<p><a href="http://vgable.com/blog/2008/05/31/messages-to-nowhere/">Sending a message that returns a <code>struct</code> to <code>nil</code> can &#8220;return&#8221; <em>undefined</em> values</a>. With small <code>struct</code>s like <code>NSRange</code>, you are more likely to get <code>{0}</code> on Intel, compared to PowerPC and iPhone/ARM. Unfortunately, this makes <code>nil</code>-messaging bugs hard to detect.  In my experience <strong>you will miss them when running on the simulator, even if they are 100% reproducible on an actual iPhone</strong>.</p>
<p>This category method has helped me avoid using <code>-rangeOfString:</code> dangerously,</p>
<pre>
@implementation NSString  (HasSubstring)
- (BOOL) hasSubstring:(NSString*)substring;
{
	if(<a href="http://vgable.com/blog/2008/12/16/isempty/">IsEmpty</a>(substring))
		return NO;
	NSRange substringRange = [self rangeOfString:substring];
	return substringRange.location != NSNotFound &#038;&#038; substringRange.length &gt; 0;
}
@end
</pre>
<p>I choose to define <code>[aString hasSubstring:@""]</code> as <code>NO</code>. You might prefer to throw an exception, or differentiate between <code>@""</code> and <code>nil</code>. But I don&#8217;t think a <code>nil</code> string is enough error to throw an exception. And even though technically any string contains the empty string, I generally treat <code>@""</code> as semantically equivalent to <code>nil</code>.</p>
<p>As <a href="http://vgable.com/blog/2008/05/31/messages-to-nowhere/">I&#8217;ve said before</a>,</p>
<blockquote><p>A few simple guidelines can help you avoid my misfortune:</p>
<ul>
<li> Be especially careful using of any objective-C method that returns a <code>double, struct,</code> or <code>long long</code>
<li> Don&#8217;t write methods that return a <code>double</code>, <code>struct</code>, or<code>long long</code>.  Return an object instead of a <code>struct</code>; an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html"><code>NSNumber*</code></a> or <code>float</code> instead of a <code>double</code> or <code>long long</code>.  If you must return a dangerous data type, then see if you can avoid it. There really isn&#8217;t a good reason to return a <code>struct</code>, except for efficiency. And when micro-optimizations like that matter, it makes more sense to write that procedure in straight-C, which avoids the overhead of Objective-C message-passing, and solves the undefined-return-value problem.
<li> But if you absolutely must return a dangerous data type, then return it in a parameter. That way you can give it a default value of your choice, and won&#8217;t have undefined values if an object is unexpectedly <code>nil</code>.<br />
Bad:<br />
<code>- (struct CStructure) evaluateThings;</code><br />
Good:<br />
<code>- (void) resultOfEvaluatingThings:(struct CStructure*)result;</code>.
</ul>
</blockquote>
<p>It&#8217;s not a bad idea to wrap up all the <code>rangeOf</code> methods in functions or categories that play safer with <code>nil</code>.</p>
<p><small>Thanks to <a href="http://www.sealiesoftware.com/">Greg Parker</a> for corrections!</small></p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2009/04/19/beware-rangeof-nsstring-operations/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

