<?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>Zach Waugh</title>
	<atom:link href="http://zachwaugh.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://zachwaugh.com</link>
	<description></description>
	<lastBuildDate>Wed, 21 Oct 2009 03:34:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>NSTextView and NSString differences in text rendering</title>
		<link>http://zachwaugh.com/2009/10/nstextview-and-nsstring-differences-in-text-rendering/</link>
		<comments>http://zachwaugh.com/2009/10/nstextview-and-nsstring-differences-in-text-rendering/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 03:09:44 +0000</pubDate>
		<dc:creator>Zach Waugh</dc:creator>
				<category><![CDATA[Cocoa/Objective-C]]></category>
		<category><![CDATA[cocoa]]></category>
		<category><![CDATA[nstextview]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://zachwaugh.com/?p=413</guid>
		<description><![CDATA[If you're drawing a string in Cocoa, you may notice discrepancies between how the text is rendered in a NSTextView and how it's rendered when using the NSString (or NSAttributedString) AppKit drawing methods. This is because of they each use a different default NSTypesetterBehavior, which results in slightly different line spacings. When you draw a [...]]]></description>
			<content:encoded><![CDATA[<p>If you're drawing a string in Cocoa, you may notice discrepancies between how the text is rendered in a NSTextView and how it's rendered when using the NSString (or NSAttributedString) AppKit drawing methods. This is because of they each use a different default NSTypesetterBehavior, which results in slightly different line spacings. When you draw a string using the drawing convenience methods - like [string drawAtPoint:point] - it uses NSTypesetterBehavior_10_2_WithCompatibility<sup>1</sup>. If you then place the same NSString (or NSAttributedString) into a NSTextView, it will look different because NSTextView uses NSTypesetterLatestBehavior. This isn't a huge problem unless you're rendering them right next to/on top of each other. For example, drawing a string into a NSCell in a NSTableView, then dynamically overlaying a NSTextView for selecting/editing. In that case, the text will jump around and it will look horrible.</p>

<p>Fortunately, after much searching, I found there is an easy solution. You need to change the typesetter behavior of the NSTextView's underlying NSLayoutManager, since I don't believe there is a way to the change the typesetter behavior of the string drawing methods.</p>

<pre>
<code class="objective-c">[[textView layoutManager] setTypesetterBehavior:NSTypesetterBehavior_10_2_WithCompatibility];</code>
</pre>

<p>That's it and your text will render exactly the same. You should also do this if you're programmatically calculating the height of a text block before drawing, or you'll get one height for the calculation, but when you draw the text, it won't fit.</p>

<p class="footnote">
 <sup>1</sup>Apple's docs that mention this: <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/TextLayout/Tasks/DrawingStrings.html#//apple_ref/doc/uid/20001808-SW1">http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/TextLayout/Tasks/DrawingStrings.html#//apple_ref/doc/uid/20001808-SW1</a>
</p>
]]></content:encoded>
			<wfw:commentRss>http://zachwaugh.com/2009/10/nstextview-and-nsstring-differences-in-text-rendering/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Debugging API requests with HTTP Client</title>
		<link>http://zachwaugh.com/2009/09/debugging-api-requests-with-http-client/</link>
		<comments>http://zachwaugh.com/2009/09/debugging-api-requests-with-http-client/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 04:01:57 +0000</pubDate>
		<dc:creator>Zach Waugh</dc:creator>
				<category><![CDATA[Cocoa/Objective-C]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[mac]]></category>

		<guid isPermaLink="false">http://zachwaugh.com/?p=367</guid>
		<description><![CDATA[I received quite a few comments on my How to use JSON in Cocoa/Objective-C post with some confusion related to the response from API calls. I thought it might help to show an example of the steps you'd take if you wanted to integrate the Twitter public timeline (or any other API) into your app [...]]]></description>
			<content:encoded><![CDATA[<p>I received quite a few comments on my <a href="http://zachwaugh.com/2009/01/how-to-use-json-in-cocoaobjective-c/">How to use JSON in Cocoa/Objective-C</a> post with some confusion related to the response from API calls. I thought it might help to show an example of the steps you'd take if you wanted to integrate the Twitter public timeline (or any other API) into your app or site. For doing any sort of HTTP/API request analysis, I first turn to HTTP Client.</p>  

<p><a href="http://ditchnet.org/httpclient/">HTTP Client</a> by Todd Ditchendorf (creator of <a href="http://fluidapp.com">Fluid</a>) has quickly become an indispensable tool for me when writing code that interacts with RESTful API web services. For building the request, HTTP Client allows to you use any of the HTTP verbs (GET, POST, PUT, DELETE, etc) as well as setting custom headers, body, and use basic authentication. The response view will show you all the headers and the raw request body. If you're still using cURL, it's time for an upgrade.</p>

<p>Typically, the biggest problem with using APIs is poor documentation. Even when the request docs are pretty good, the response docs often fall short. Either they don't document the response at all, only document a portion of it, or only show it in one format. So my first step in implementing some API code is looking at the docs, and seeing how the request is formed. Twitter has a simple API, and pretty good documentation, so it's easy to figure out how to get the public timeline as JSON on this page <a href="http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-public_timeline">http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-public_timeline</a>. The URL for this request is just "http://twitter.com/statuses/public_timeline.json" and the HTTP method is "GET".</p>

<a href="/images/posts/http_client.png" class="zoom right" title="HTTP Client screenshot"><img src="/images/posts/http_client_thumb.png" alt="HTTP Client" /></a>
<p>The next step is firing up HTTP Client and making the request to see what it looks like <small>(see screenshot to the right)</small>. Twitter is a simple case where you shouldn't have trouble, but for more complex APIs with a lot of options (like the <a href="http://code.google.com/apis/analytics/docs/gdata/gdataReferenceDataFeed.html">Google Analytics API</a>), it might take a bit of trial and error to get the exact data you're after. It's much quicker to iterate in HTTP Client to get your requests working right than to try to do so in code. This will allow you to get your request formatted correctly, and find any problems, like authentication errors or unexpected redirects, right away.</p>

<p>Once I have the correct request, the final step is to look at the structure of the response so I know how to parse it. I prefer to use JSON whenever possible, so it's mostly seeing what is an array, what is an object, and how things are nested. HTTP Client seems to do a pretty good job with syntax highlighting of XML and HTML responses that make them nice and readable, but unfortunately not with JSON. A quick solution is to copy the response, paste it into TextMate, set the document as JSON, and use JSON-> Reformat Document. <small>(You'll need the JSON bundle to do that)</small> That will give you a nice, readable view of the structure.</p>

<a href="/images/posts/textmate_json.png" class="zoom right" title="JSON formatted with TextMate"><img src="/images/posts/textmate_json_thumb.png" alt="HTTP Client" /></a>
<p>In the screenshot to the right, you can see the JSON response of the public Twitter timeline. By looking at the response, I can immediately see first off, that the main structure is an array. The elements of the array are status objects and each status object contains a user object. Without looking at the formatted response first, it might not be obvious that the user is a nested object of the status.</p> 

<p>That's it. Now I know exactly how the request and response are formatted, and I can easily write the implementation code without any surprises. It seems like a bit of work, but it's all of 5 minutes when you're familiar with the process, and is much faster than trying to locate a bug in code that's really due to a malformed request or unexpected response structure.</p>]]></content:encoded>
			<wfw:commentRss>http://zachwaugh.com/2009/09/debugging-api-requests-with-http-client/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating an archives page with WordPress</title>
		<link>http://zachwaugh.com/2009/05/creating-an-archives-page-with-wordpress/</link>
		<comments>http://zachwaugh.com/2009/05/creating-an-archives-page-with-wordpress/#comments</comments>
		<pubDate>Tue, 12 May 2009 03:33:58 +0000</pubDate>
		<dc:creator>Zach Waugh</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://zachwaugh.com/?p=242</guid>
		<description><![CDATA[
I don't really see the usefulness in viewing blog archives by month or year.  I'm not particulary interested in what someone wrote in November 2008. If I'm looking at your blog, I care what you write about, not when1. I'm not sure why so many blogging systems make a monthly display the default for [...]]]></description>
			<content:encoded><![CDATA[<p>
I don't really see the usefulness in viewing blog archives by month or year.  I'm not particulary interested in what someone wrote in November 2008. If I'm looking at your blog, I care <em>what</em> you write about, not <em>when</em><sup>1</sup>. I'm not sure why so many blogging systems make a monthly display the default for archives, when a list of the posts is much more usable.
</p>

<p>Fortunately, this is really easy to accomplish with WordPress. Take a look at my <a href="http://zachwaugh.com/archives">archives page</a> for an example. This list all the posts I've written from newest to oldest. Someone can instantly took a look and see if there is something they want to read.</p>

<p>
<a href="http://zachwaugh.com/wp-content/uploads/archives_template.png" class="zoom right" title="Screenshot of setting template"><img src="http://zachwaugh.com/wp-content/uploads/archives_template-150x106.png" alt="archives_template" width="150" height="106" class="alignnone size-thumbnail wp-image-244" /></a>
To create an archives page, create a new "Page", and set the template to "Archives" <small>(see image)</small>.  This should appear automatically in the dropdown, if it doesn't, create an archives.php file in your current theme, and make sure there is a header like this:</p>

<pre>
<code class="php">&lt;?php
/*
Template Name: Archives
*/
?&gt;
</code>
</pre>

<p>
Once you save that page, if you're using the default WordPress archives.php, it will list "Archives by Month" and "Archives by Subject". Edit the archives.php file, remove those sections, and add the following code:
</p>

<pre>
<code class="php">&lt;? $posts = get_posts(&#x27;numberposts=-1&#x27;);
  foreach ($posts as $post) :
     setup_postdata($post);
  ?&gt;
    &lt;div class=&quot;post&quot; id=&quot;post-&lt;?php the_ID(); ?&gt;&quot;&gt;
      &lt;h2&gt;&lt;a href=&quot;&lt;?php the_permalink() ?&gt;&quot; rel=&quot;bookmark&quot; title=&quot;Permalink to &lt;?php the_title_attribute(); ?&gt;&quot;&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;
      &lt;p class=&quot;date_comments&quot;&gt;&lt;?php the_time(&#x27;M j, Y&#x27;); ?&gt; - &lt;?php comments_number(&#x27;0 Comments&#x27;, &#x27;1 Comment&#x27;, &#x27;% Comments&#x27;, &#x27;comments_count&#x27;); ?&gt;&lt;/p&gt;
    &lt;/div&gt;
&lt;? endforeach; ?&gt;</code>
</pre>

<p>
Of course, you'll want to adjust this for your own site as this formatting is specific to my site. Now you have a nice, useful page with all your posts clearly displayed. I'm a proponent of this view even if you have a couple hundred posts, I'd still like to be able to see everything in one shot.
</p>

<p class="footnote">
<sup>1</sup> Of course I actually do care when it was written, especially if it's technology related. If it was written in 2001, it may be obsolete, but I'm not going to find content based on date.
</p>]]></content:encoded>
			<wfw:commentRss>http://zachwaugh.com/2009/05/creating-an-archives-page-with-wordpress/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Dropbox to sync TextMate</title>
		<link>http://zachwaugh.com/2009/04/using-dropbox-to-sync-textmate/</link>
		<comments>http://zachwaugh.com/2009/04/using-dropbox-to-sync-textmate/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 01:25:48 +0000</pubDate>
		<dc:creator>Zach Waugh</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[textmate]]></category>

		<guid isPermaLink="false">http://zachwaugh.com/?p=212</guid>
		<description><![CDATA[
I use TextMate at both home and work for doing all my development and for dealing with pretty much anything text related. I got tired of having inconsistent environments between work and home. I wanted to be able to create a new snippet at work and be able to use it at home (and vice [...]]]></description>
			<content:encoded><![CDATA[<p>
I use <a href="http://www.macromates.com">TextMate</a> at both home and work for doing all my development and for dealing with pretty much anything text related. I got tired of having inconsistent environments between work and home. I wanted to be able to create a new snippet at work and be able to use it at home (and vice versa) without having to recreate it. Turns out you can do this easily with Dropbox.
</p>

<p>
<a href="http://www.getdropbox.com">Dropbox<sup>1</sup></a> is a service to sync files across multiple computers and to the cloud, and It's free to use with 2GB of storage. It makes it dead simple to keep files in sync and you can access those files from the web as well. All you have to do is store your TextMate specific files in your Dropbox account, and then point TextMate to use those files. 
</p>

<ol>
<li><p><span class="step_number">1.</span> Quit TextMate if you have it running</p></li>
<li><p><span class="step_number">2.</span> Move the ~/Library/Application Support/TextMate folder to your Dropbox</p></li>
<li><p><span class="step_number">3.</span> Open up Terminal and create a symbolic link from your ~/Dropbox/TextMate folder to your ~/Library/Application Support folder:</p></li>
<li><pre><code>$ ln -s ~/Dropbox/TextMate ~/Library/Application\ Support/TextMate</code></pre></li>
<li><p><span class="step_number">4.</span> Repeat steps 1-3 on all the computers you want to sync.</p></li>
</ol>
<p>
Now any changes you make to your TextMate bundles on any computer will be synced across all your machines. For this to work transparently, you'll want to make sure Dropbox is running at login.
</p>

<p class="footnote">
<sup>1</sup>If you don't have a Dropbox account, sign up using <a href="https://www.getdropbox.com/referrals/NTU0NjAxOTk">this link</a> and we both get extra storage space for free.
</p>]]></content:encoded>
			<wfw:commentRss>http://zachwaugh.com/2009/04/using-dropbox-to-sync-textmate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Opening links in background with Cocoa</title>
		<link>http://zachwaugh.com/2009/04/opening-links-in-background-with-cocoa/</link>
		<comments>http://zachwaugh.com/2009/04/opening-links-in-background-with-cocoa/#comments</comments>
		<pubDate>Tue, 07 Apr 2009 00:11:29 +0000</pubDate>
		<dc:creator>Zach Waugh</dc:creator>
				<category><![CDATA[Cocoa/Objective-C]]></category>
		<category><![CDATA[Usability]]></category>
		<category><![CDATA[cocoa]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://zachwaugh.com/?p=184</guid>
		<description><![CDATA[One of my biggest annoyances with mac software is how it handles opening links. This is usually a disruptive process that requires you to switch from your current task and application to another. Since I use spaces to partition apps (more info), it often results in not only switching apps, but also spaces, which makes [...]]]></description>
			<content:encoded><![CDATA[<p>One of my biggest annoyances with mac software is how it handles opening links. This is usually a disruptive process that requires you to switch from your current task and application to another. Since I use spaces to partition apps (<a href="http://www.fastspot.com/blog/2009/01/my-setup/">more info</a>), it often results in not only switching apps, but also spaces, which makes it all the more annoying. Now, it makes sense if you click a link, that you want to view that page right away, but usually I'm not opening links to read them now, but to read them <em>soon</em>.</p>

<p>For example, if I'm reading an email that has links, I want to open them as I read it so I don't forget to look at them, but I don't want to have to switch applications mid-sentence just to open a url. This is even more prevalent when reading feeds. I use NetNewsWire for my RSS reader, but I don't use it to actually read the content. I <em>like</em> going to the site. I just use an RSS reader as means to get there more efficiently. So as I go through the links, if there is something interesting, I open the link. When I've gone through all the new items, I have everything open in tabs in Firefox. I find it too jarring to open a link, read it, go back to NNW, open a link, read it, etc. NNW handles this with ease by having a "Open links in background" preference. A simple one checkbox option that makes the experience all that more enjoyable and seamless for me.</p>

<p>So, to all developers out there, if your app involves people opening links, please provide this functionality. It's the attention to detail on these types of user interactions that really make or break an application. And so there's no excuse, here's an objective-c method to do it for you:</p>

<pre>
<code class="objective-c">// Opens a URL in the default browser in background or foreground
- (void)openURL:(NSString *)url inBackground:(BOOL)background
{
  if (background)
  {
    NSArray* urls = [NSArray arrayWithObject:[NSURL URLWithString:url]];
    [[NSWorkspace sharedWorkspace] openURLs:urls withAppBundleIdentifier:nil options:NSWorkspaceLaunchWithoutActivation additionalEventParamDescriptor:nil launchIdentifiers:nil];    
  }
  else
  {
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:url]];
  }
}
</code>
</pre>

<p>12 lines of code and your app just became 10x more useful to me. While we're on links and usability. If your app does implement this functionality, make sure to provide some indication that the click actually worked or users will keep clicking the link all the while opening the same page a hundred times in their browser. NetNewsWire handles this by providing a subtle animation and changing the color of the text of the links you opened.</p>]]></content:encoded>
			<wfw:commentRss>http://zachwaugh.com/2009/04/opening-links-in-background-with-cocoa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Programmatically retrieving IP Address of iPhone</title>
		<link>http://zachwaugh.com/2009/03/programmatically-retrieving-ip-address-of-iphone/</link>
		<comments>http://zachwaugh.com/2009/03/programmatically-retrieving-ip-address-of-iphone/#comments</comments>
		<pubDate>Sat, 14 Mar 2009 21:01:21 +0000</pubDate>
		<dc:creator>Zach Waugh</dc:creator>
				<category><![CDATA[Cocoa/Objective-C]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[cocoa]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://zachwaugh.com/?p=178</guid>
		<description><![CDATA[
For my app, QuickPic, I needed to show the user the IP address of their iPhone so they could type in the URL to the browser. The iPhone SDK provided no simple way to get the IP Address for the wifi connection. There are some undocumented methods that work ([NSHost addresses]), but I didn't want [...]]]></description>
			<content:encoded><![CDATA[<p>
For my app, <a href="http://www.quickpicapp.com">QuickPic</a>, I needed to show the user the IP address of their iPhone so they could type in the URL to the browser. The iPhone SDK provided no simple way to get the IP Address for the wifi connection. There are some undocumented methods that work ([NSHost addresses]), but I didn't want to risk them pulling that out of there and my app breaking. So I wrote some C code (cobbled together from various sources) that will loop through the network interfaces and retrieve the IP address.
</p>

<p class="code_header">
Here's an Objective-C method to retrieve the IP address of the wifi connection as a NSString.
</p>

<code class="objective-c">- (NSString *)getIPAddress
{
  NSString *address = @"error";
  struct ifaddrs *interfaces = NULL;
  struct ifaddrs *temp_addr = NULL;
  int success = 0;

  // retrieve the current interfaces - returns 0 on success
  success = getifaddrs(&#038;interfaces);
  if (success == 0)
  {
    // Loop through linked list of interfaces
    temp_addr = interfaces;
    while(temp_addr != NULL)
    {
      if(temp_addr->ifa_addr->sa_family == AF_INET)
      {
        // Check if interface is en0 which is the wifi connection on the iPhone
        if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
        {
          // Get NSString from C String
          address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
        }
      }

      temp_addr = temp_addr->ifa_next;
    }
  }

  // Free memory
  freeifaddrs(interfaces);

  return address;
}
</code>

<p class="code_header">
<strong>Update (7/10/09):</strong> if this isn't working for you you may need to include the following C headers in the top of your class implementation as well
</p>
<code class="objective-c">#include &lt;ifaddrs.h&gt;
#include &lt;arpa/inet.h&gt;</code>

<p>
Note: this code will work with the Simulator as well though the interface may not be en0. The iPhone Simulator seems to just use the underlying active Mac OS X network interface. On my macbook pro using wifi, this is en1, but your mileage may vary.
</p>
<p>
This will also work in Mac OS X since the iPhone OS and Mac OS X both use a lot of the same unix underpinnings. 
</p>]]></content:encoded>
			<wfw:commentRss>http://zachwaugh.com/2009/03/programmatically-retrieving-ip-address-of-iphone/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How to use JSON in Cocoa/Objective-C</title>
		<link>http://zachwaugh.com/2009/01/how-to-use-json-in-cocoaobjective-c/</link>
		<comments>http://zachwaugh.com/2009/01/how-to-use-json-in-cocoaobjective-c/#comments</comments>
		<pubDate>Mon, 12 Jan 2009 00:42:31 +0000</pubDate>
		<dc:creator>Zach Waugh</dc:creator>
				<category><![CDATA[Cocoa/Objective-C]]></category>
		<category><![CDATA[cocoa]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://zachwaugh.com/?p=90</guid>
		<description><![CDATA[
Using JSON in Cocoa is simple thanks to an excellent  open-source JSON Framework by Stig Brautaset. The framework will decode a JSON string into native Objective-C objects, and vice versa . The project includes a packaged Framework, Mac and iPhone SDKs, as well as the source code. The easiest method is to directly embed [...]]]></description>
			<content:encoded><![CDATA[<p>
Using <a href="http://www.json.org">JSON</a> in Cocoa is simple thanks to an excellent <a href="http://code.google.com/p/json-framework/"> open-source JSON Framework by Stig Brautaset</a>. The framework will decode a JSON string into native Objective-C objects, and vice versa . The project includes a packaged Framework, Mac and iPhone SDKs, as well as the source code. The easiest method is to directly embed the source in your app as it's pretty lightweight, and will work on both Mac and iPhone apps. Here are step-by-step instructions on how to use JSON in your app. <small>(click the images to enlarge)</small>
</p>
<br />
<div class="block">
<p>
<a href="http://zachwaugh.com/files/cocoa_step1.png"  title="click to zoom" class="zoom right"><img src="http://zachwaugh.com/files/cocoa_step1_thumb.png" alt="cocoa-json_step1" title="cocoa-json_step1" width="150" class="thumbnail" /></a>
1.) Download the latest version (currently 2.2.1) from <a href="http://code.google.com/p/json-framework/downloads/list">http://code.google.com/p/json-framework/downloads/list</a>
</p>
</div>

<div class="block">
<a href="http://zachwaugh.com/files/cocoa_step2.png" title="click to zoom" class="zoom right"><img src="http://zachwaugh.com/files/cocoa_step2_thumb.png" alt="cocoa-json_step2" title="cocoa-json_step2" width="150" class="thumbnail" /></a>
<p>
2.) Open the dmg, and drag the JSON folder into your project in Xcode. Check "Copy items into destination group's folder (if needed)" when prompted.
</p>
</div>

<div class="block">
<p>
3.) Once the source is embedded into your project, you need to import the framework to use it in your code</p>
<pre><code class="objective-c">#import "JSON.h"</code></pre>
</div>

<div class="block">
<p>
4.) Create a SBJSON object to parse JSON into a native Cocoa object. SBJSON will return either a NSDictionary or NSArray depending on the structure of the data. You should know ahead of time the structure of the JSON object your parsing and whether it's a single JSON object or an array of JSON objects and use the appropriate Cocoa class.
</p>
<pre>
<code class="objective-c">// Create SBJSON object to parse JSON
SBJSON *parser = [[SBJSON alloc] init];
	
// parse the JSON string into an object - assuming json_string is a NSString of JSON data
NSDictionary *object = [parser objectWithString:json_string error:nil];
</code>
</pre>
</div>

<div class="block">

<p>Here's an example showing how to download the public timeline from Twitter as JSON and parse it.</p>
<pre>
<code class="objective-c">// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];

// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://twitter.com/statuses/public_timeline.json"]];

// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];

// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
  // You can retrieve individual values using objectForKey on the status NSDictionary
  // This will print the tweet and username to the console
  NSLog(@"%@ - %@", [status objectForKey:@"text"], [[status objectForKey:@"user"] objectForKey:@"screen_name"]);
}</code>
</pre>
</div>

<p><strong>Update (9/16/09):</strong> I just wrote a post about debugging API requests that might be helpful if you're having problems using this with another API - <a href="http://zachwaugh.com/2009/09/debugging-api-requests-with-http-client/">Debugging API requests with HTTP Client</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://zachwaugh.com/2009/01/how-to-use-json-in-cocoaobjective-c/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>JSON output in Rails 2.1</title>
		<link>http://zachwaugh.com/2008/11/json-output-in-rails-21/</link>
		<comments>http://zachwaugh.com/2008/11/json-output-in-rails-21/#comments</comments>
		<pubDate>Tue, 04 Nov 2008 02:10:16 +0000</pubDate>
		<dc:creator>Zach Waugh</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://zachwaugh.com/?p=68</guid>
		<description><![CDATA[I just came across a change in Rails 2.1 when converting an ActiveRecord object to JSON. The JSON output now includes the ActiveRecord model name in the object so if you have a user model and convert it to json, you get the following:


user = User.find(1)
user.to_json
{"user" : {"name" : "John Doe", "id" : 1}}



This becomes [...]]]></description>
			<content:encoded><![CDATA[<p>I just came across a change in Rails 2.1 when converting an ActiveRecord object to JSON. The JSON output now includes the ActiveRecord model name in the object so if you have a user model and convert it to json, you get the following:</p>

<pre>
<code class="ruby">user = User.find(1)
user.to_json
{"user" : {"name" : "John Doe", "id" : 1}}
</code>
</pre>

<p>This becomes a pain when you're pulling this data via AJAX and you're doing something like this:</p>
<pre>
<code class="ruby">def show
  user = User.find(params[:id])

  # to_json is called automatically so you don't need to call it explicitly
  render :json => {:status => 'ok', :user => user}
end
</code>
</pre>
<p></p>

<p>In your client side code, you then have to type user twice, once for the hash key, and once for the ActiveRecord model name, to get to the user's attributes:</p>

<pre>
<code class="javascript">$.getJSON(url, function(json){
  if(json.status == 'ok')
  {
     // do something with user data
     alert(json.user.user.name);
  }
});
</code>
</pre>

<p>Unnecessarily redundant and inconvenient. This seems to have been changed in Rails 2.1, but the old behavior can be restored by editing config/initializers/new_rails_default.rb and changing:</p>

<pre>
<code class="ruby"># Include Active Record class name as root for JSON serialized output.
ActiveRecord::Base.include_root_in_json = true
</code>
</pre>

<p>to</p> 

<pre>
<code class="ruby"># Include Active Record class name as root for JSON serialized output.
ActiveRecord::Base.include_root_in_json = false
</code>
</pre>

<p>Restart your app, and you'll now get just the attributes for the model and not the model name.</p>]]></content:encoded>
			<wfw:commentRss>http://zachwaugh.com/2008/11/json-output-in-rails-21/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Ext3 filesystem sub-directory limit</title>
		<link>http://zachwaugh.com/2008/11/xt3-filesystem-sub-directory-limit/</link>
		<comments>http://zachwaugh.com/2008/11/xt3-filesystem-sub-directory-limit/#comments</comments>
		<pubDate>Sat, 01 Nov 2008 19:52:19 +0000</pubDate>
		<dc:creator>Zach Waugh</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[linux]]></category>

		<guid isPermaLink="false">http://zachwaugh.com/?p=55</guid>
		<description><![CDATA[I recently came across a problem on a site where a client could no longer upload images through their site. After digging through the logs, I found the relevant error:

Errno::EMLINK (Too many links - /usr/lib/ruby/1.8/fileutils.rb:243:in `mkdir'

This error was occurring when the system tried to make a new directory to store the uploaded images in. After [...]]]></description>
			<content:encoded><![CDATA[<p>I recently came across a problem on a site where a client could no longer upload images through their site. After digging through the logs, I found the relevant error:</p>

<blockquote><p>Errno::EMLINK (Too many links - /usr/lib/ruby/1.8/fileutils.rb:243:in `mkdir'</p></blockquote>

<p>This error was occurring when the system tried to make a new directory to store the uploaded images in. After researching (googling) the error, I find out that the <a href="http://en.wikipedia.org/wiki/Ext3">Linux ext3 filesystem</a> can only have a maximum of 32,000 links per inode which means a directory can only have 31,998 sub-directories. It just so happens that this particularly directory had exactly 31,998 directories in it.</p>

<p>When a user uploaded an image, multiple sizes were generated, and a directory was created to hold all the images for a particular item. The directory could never be created due to a filesystem error, so the upload was failing. To fix this problem, you can use a different filesystem without this limitation or I believe you can patch ext3 to support more inode links. But of course the easiest solution is partitioning your data, which is what I did. Fixing this problem required some relatively minor re-architecture of the app by partitioning the items into different sub-directories to avoid the ext3 limit.</p>]]></content:encoded>
			<wfw:commentRss>http://zachwaugh.com/2008/11/xt3-filesystem-sub-directory-limit/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Quick way to fix accidentally deleted .svn directories</title>
		<link>http://zachwaugh.com/2008/09/quick-way-to-fix-accidentally-deleted-svn-directories/</link>
		<comments>http://zachwaugh.com/2008/09/quick-way-to-fix-accidentally-deleted-svn-directories/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 00:30:55 +0000</pubDate>
		<dc:creator>Zach Waugh</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[subversion]]></category>

		<guid isPermaLink="false">http://zachwaugh.com/?p=40</guid>
		<description><![CDATA[If you acccidentally delete a .svn directory from a folder that is under version control, you'll get an error when you try to commit and won't be able to proceed. A real quick fix, that worked for me, is to just check out a new copy of the repository, and copy the .svn directory you [...]]]></description>
			<content:encoded><![CDATA[<p>If you acccidentally delete a .svn directory from a folder that is under version control, you'll get an error when you try to commit and won't be able to proceed. A real quick fix, that worked for me, is to just check out a new copy of the repository, and copy the .svn directory you deleted to your current working copy and you should be able to commit.</p>

<code>$ svn co svn://server/project project
$ mv project/path/to/dir/.svn working_copy/path/to/dir
$ chmod -R 777 working_copy/path/to/dir
</code>

<p>You may not need the chmod 777, but I was getting a permission denied error before that. I don't know what negative effects this could have on your repository, so proceed at your own risk.</p>]]></content:encoded>
			<wfw:commentRss>http://zachwaugh.com/2008/09/quick-way-to-fix-accidentally-deleted-svn-directories/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
