<?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>iPhone Programming Tutorials &#187; Tutorials</title>
	<atom:link href="/category/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://icodeblog.com</link>
	<description>iPhone Programming Tutorials</description>
	<lastBuildDate>Tue, 19 Nov 2013 19:34:46 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.2.3</generator>
	<item>
		<title>Debugging a memory increase, using Generational Analysis</title>
		<link>http://icodeblog.com/2013/11/19/debugging-a-memory-increase-using-generational-analysis/</link>
		<comments>http://icodeblog.com/2013/11/19/debugging-a-memory-increase-using-generational-analysis/#comments</comments>
		<pubDate>Tue, 19 Nov 2013 19:34:46 +0000</pubDate>
		<dc:creator><![CDATA[James Van Metre]]></dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=4556</guid>
		<description><![CDATA[I was recently working on an internal project for Burnside Digital, and decided it was time to do some memory profiling to make sure that I didn&#8217;t have any leaks. I ran the program with the &#8216;Leaks&#8217; tool of instruments, and as I was watching the Live Bytes column, I saw the number of Bytes being used, slowly but surely increasing as time went on. Instruments wasn&#8217;t detecting any leaks, so I knew this wasn&#8217;t going to be a straightforward leak  ...]]></description>
				<content:encoded><![CDATA[<p>I was recently working on an internal project for Burnside Digital, and decided it was time to do some memory profiling to make sure that I didn&#8217;t have any leaks. I ran the program with the &#8216;Leaks&#8217; tool of instruments, and as I was watching the Live Bytes column, I saw the number of Bytes being used, slowly but surely increasing as time went on. Instruments wasn&#8217;t detecting any leaks, so I knew this wasn&#8217;t going to be a straightforward leak to debug.</p>
<p>At that point I decided to use the very handy &#8220;Mark Generation&#8221; button in instruments. For those of you that haven&#8217;t used this button before, what it does is take a snapshot of all the active objects when you tap it. As objects get deallocated, they get removed from the snapshot. The usefulness of this snapshot is for doing a generational analysis of your application. Taking subsequent snapshots of the memory state of your application will show you what objects are still hanging around when they are supposed to be deallocated.</p>
<p><a href="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.15.52-AM.png"><img class="alignnone size-medium wp-image-1759" alt="Screen Shot 2013-11-19 at 9.15.52 AM" src="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.15.52-AM-300x220.png" width="300" height="220" /></a><a href="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.16.25-AM.png"><img class="alignnone size-medium wp-image-1758" alt="Screen Shot 2013-11-19 at 9.16.25 AM" src="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.16.25-AM-300x220.png" width="300" height="220" /></a></p>
<p>As you can see in the screenshots, the first Generation will be all the objects currently in memory. On each subsequent generation, it is only the objects that have been created, and not deallocated yet, that are shown. In Generation H this screenshot was right after I created the generation so it shows a larger growth. Waiting a few more seconds, it&#8217;s growth also dropped to 1.58 KB, with 32 objects.</p>
<p>Immediately I realized, that indeed, I have a fairly large issue, in that roughly every 10 seconds, I was creating and not destroying 1.5 KB&#8230; In a long running app, this could really add up.</p>
<p>Now I had to try to debug these increases. If you tap on the grey right arrow next to a generation, it will expand out and show you all the objects still hanging around.</p>
<p><a href="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.22.28-AM.png"><img class="alignnone size-medium wp-image-1760" alt="Screen Shot 2013-11-19 at 9.22.28 AM" src="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.22.28-AM-300x220.png" width="300" height="220" /></a></p>
<p>Hrmm, lots of Core Foundation objects, some NSURL&#8217;s, and a bunch of strings. None of this is my code. Let&#8217;s dig deeper. You can expand each of the types of objects to see all the addresses that are hanging around, and see the stack trace for each of those objects. You do this by looking at the extended detail of the objects, by selecting the third button on the right in the View area to open the Extended Detail.</p>
<p><a href="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.36.38-AM.png"><img class="alignnone size-medium wp-image-1762" alt="Screen Shot 2013-11-19 at 9.36.38 AM" src="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.36.38-AM-300x220.png" width="300" height="220" /></a><img class="alignnone size-medium wp-image-1761" alt="Screen Shot 2013-11-19 at 9.28.34 AM" src="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.28.34-AM-300x220.png" width="300" height="220" /></p>
<p>Looking at the stack traces for a bunch of objects, I see a lot of internal Core Foundation traces, which don&#8217;t help, but then I came across a helpful stack trace pointing me at PNReachability. Looking through all the traces of the objects hanging around, the only user land code, was pointing at PNReachability.</p>
<p>Going one level further down, we can see all the retain / release and autoreleases that this object has experienced. Also lets look at the code</p>
<p><a href="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.40.04-AM.png"><img class="alignnone size-medium wp-image-1763" alt="Screen Shot 2013-11-19 at 9.40.04 AM" src="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.40.04-AM-300x158.png" width="300" height="158" /></a><a href="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.45.32-AM.png"><img class="alignnone size-medium wp-image-1764" alt="Screen Shot 2013-11-19 at 9.45.32 AM" src="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.45.32-AM-300x181.png" width="300" height="181" /></a></p>
<p>One of the components we use is a pub/sub implementation called PubNub. Since this bug seemed to be in that component, I decided to see if I couldn&#8217;t replicate it with the demo example of PubNub from https://github.com/pubnub/objective-c/tree/master/iOS at commit  f9e7d59.</p>
<p>Profiling the demo, I was able to see the same 1.58 kb increases every 10 seconds, so I knew that my app wasn&#8217;t at fault.</p>
<p><a href="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.55.42-AM.png"><img class="alignnone size-medium wp-image-1766" alt="Screen Shot 2013-11-19 at 9.55.42 AM" src="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.55.42-AM-300x220.png" width="300" height="220" /></a><img class="alignnone size-medium wp-image-1765" alt="Screen Shot 2013-11-19 at 9.56.05 AM" src="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-9.56.05-AM-300x220.png" width="300" height="220" /></p>
<p>Looking at the code for handleOriginLookupTimer, i see the pretty standard dispatch_async on a background thread, running a synchronous network call, and then calling back to the main thread on another dispatch_async. They are even doing a weak reference to self properly.</p>
<div class="wp_syntax">

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>handleOriginLookupTimer <span style="color: #002200;">&#123;</span>
&nbsp;
    <span style="color: #11740a; font-style: italic;">// In case if reachability report that connection is available (not on cellular) we should launch additional lookup service which will</span>
    <span style="color: #11740a; font-style: italic;">// allow to check network state for sure</span>
<span style="color: #6e371a;">#if __IPHONE_OS_VERSION_MIN_REQUIRED</span>
    <span style="color: #a61390;">BOOL</span> shouldSuspectWrongState <span style="color: #002200;">=</span> self.reachabilityStatus <span style="color: #002200;">!=</span> PNReachabilityStatusReachableViaCellular;
<span style="color: #6e371a;">#else</span>
    <span style="color: #a61390;">BOOL</span> shouldSuspectWrongState <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
<span style="color: #6e371a;">#endif</span>
&nbsp;
    <span style="color: #11740a; font-style: italic;">// In case if server report that there is connection</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self isServiceAvailableForStatus<span style="color: #002200;">:</span>self.reachabilityStatus<span style="color: #002200;">&#93;</span> <span style="color: #002200;">&amp;&amp;</span> shouldSuspectWrongState<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
&nbsp;
        __block __pn_desired_weak __typeof<span style="color: #002200;">&#40;</span>self<span style="color: #002200;">&#41;</span> weakSelf <span style="color: #002200;">=</span> self;
        dispatch_async<span style="color: #002200;">&#40;</span>dispatch_get_global_queue<span style="color: #002200;">&#40;</span>DISPATCH_QUEUE_PRIORITY_DEFAULT, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
&nbsp;
            <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>requestError;
            <span style="color: #400080;">NSHTTPURLResponse</span> <span style="color: #002200;">*</span>response;
            <span style="color: #400080;">NSMutableURLRequest</span> <span style="color: #002200;">*</span>timeTokenRequest <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableURLRequest</span> alloc<span style="color: #002200;">&#93;</span> initWithURL<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> URLWithString<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>PNNetworkHelper originLookupResourcePath<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
            timeTokenRequest.timeoutInterval <span style="color: #002200;">=</span> kPNReachabilityOriginLookupTimeout;
            <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>downloadedTimeTokenData <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURLConnection</span> sendSynchronousRequest<span style="color: #002200;">:</span>timeTokenRequest returningResponse<span style="color: #002200;">:&amp;</span>response error<span style="color: #002200;">:&amp;</span>requestError<span style="color: #002200;">&#93;</span>;
<span style="color: #11740a; font-style: italic;">//            [[NSURLCache sharedURLCache] removeCachedResponseForRequest:timeTokenRequest];</span>
&nbsp;
            dispatch_async<span style="color: #002200;">&#40;</span>dispatch_get_main_queue<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
&nbsp;
                <span style="color: #002200;">&#91;</span>weakSelf handleOriginLookupCompletionWithData<span style="color: #002200;">:</span>downloadedTimeTokenData response<span style="color: #002200;">:</span>response error<span style="color: #002200;">:</span>requestError<span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

</div>
<p>All pretty standard, but since the bug was there, and I know that blocks within blocks can lead to retain cycles, I tried to make sure there weren&#8217;t any, that were causing this issue.</p>
<p>I went through several iterations of turning the requestError, response, and downloadedTimeTokenData into weak references, and then back into strong ones, to see if any change to those would fix this 1.58 kb leak. I tried moving the declarations of the objects outside both blocks, and several other things that would break a retain cycle if it existed, but nothing I was doing worked.  The problem didn&#8217;t seem to be a retain cycle.</p>
<p>My next step was the always helpful google searching. I searched for  various combinations of sendSynchronousRequest, dispatch_async, iOS Block&#8230; and so on trying to see if anyone else had this strange issue.</p>
<p>I finally found <a href="http://stackoverflow.com/questions/3116205/getting-leak-in-leak-in-nsurlconnection-sendsynchronousrequesttherequest-retur">http://stackoverflow.com/questions/3116205/getting-leak-in-leak-in-nsurlconnection-sendsynchronousrequesttherequest-retur</a> which the comments pointed to NSURLCache as being the culprit.</p>
<div class="wp_syntax">

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="diff" style="font-family:monospace;">diff --git a/iOS/iPadDemoApp/pubnub/libs/PubNub/Network/PNReachability.m b/iOS/iPadDemoApp/pubnub/libs/PubNub/Network/PNReachability.m
index ee4fdcc..bf<span style="color: #440088;">457d5</span> <span style="">100644</span>
<span style="color: #888822;">--- a/iOS/iPadDemoApp/pubnub/libs/PubNub/Network/PNReachability.m</span>
<span style="color: #888822;">+++ b/iOS/iPadDemoApp/pubnub/libs/PubNub/Network/PNReachability.m</span>
<span style="color: #440088;">@@ -476,6 +476,7 @@ void PNReachabilityCallback<span style="">&#40;</span>SCNetworkReachabilityRef reachability __unused, SCNe</span>
             NSMutableURLRequest *timeTokenRequest = <span style="">&#91;</span><span style="">&#91;</span>NSMutableURLRequest alloc<span style="">&#93;</span> initWithURL:<span style="">&#91;</span>NSURL URLWithString:<span style="">&#91;</span>PNNetworkHelper originLookupResourcePath<span style="">&#93;</span><span style="">&#93;</span><span style="">&#93;</span>;
             timeTokenRequest.timeoutInterval = kPNReachabilityOriginLookupTimeout;
             NSData *downloadedTimeTokenData = <span style="">&#91;</span>NSURLConnection sendSynchronousRequest:timeTokenRequest returningResponse:&amp;response error:&amp;requestError<span style="">&#93;</span>;
<span style="color: #00b000;">+            <span style="">&#91;</span><span style="">&#91;</span>NSURLCache sharedURLCache<span style="">&#93;</span> removeCachedResponseForRequest:timeTokenRequest<span style="">&#93;</span>;</span>
&nbsp;
             dispatch_async<span style="">&#40;</span>dispatch_get_main_queue<span style="">&#40;</span><span style="">&#41;</span>, ^<span style="">&#123;</span></pre></td></tr></table></div>

</div>
<p>After a simple addition of removeCachedResponseForRequest, after the sendSynchronousRequest I was able to fix the 1.58kb heap growth every 10 seconds.</p>
<p><a href="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-10.41.02-AM.png"><img class="alignnone size-medium wp-image-1767" alt="Screen Shot 2013-11-19 at 10.41.02 AM" src="http://blogs.burnsidedigital.com/wp-content/uploads/2013/11/Screen-Shot-2013-11-19-at-10.41.02-AM-300x164.png" width="300" height="164" /></a></p>
<p>For more information on using the Mark Generation tool, or instruments in general, check out the WWDC 2013 session 410 &#8220;Fixing Memory Issues&#8221;.</p>
<!-- Start Sociable --><div class="sociable"><ul class='clearfix'></ul><div onMouseout="fixOnMouseOut(this,event,'post-4556')" id="sociable-post-4556" style="display:none;">   

    <div style="top: auto; left: auto; display: block;" id="sociable">



		<div class="popup">

			<div class="content">

				<ul><li style="heigth:32px;width:32px"><a title="Facebook" class="option1_32" style="background-position:-96px 0px" rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;t=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis"></a></li><li style="heigth:32px;width:32px"><a title="Myspace" class="option1_32" style="background-position:0px -32px" rel="nofollow" target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;t=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis"></a></li><li style="heigth:32px;width:32px"><a title="Twitter" class="option1_32" style="background-position:-288px -32px" rel="nofollow" target="_blank" href="http://twitter.com/intent/tweet?text=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis%20-%20http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F%20  SHARETAG"></a></li><li style="heigth:32px;width:32px"><a title="LinkedIn" class="option1_32" style="background-position:-288px 0px" rel="nofollow" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;title=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis&amp;source=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials&amp;summary=I%20was%20recently%20working%20on%20an%20internal%20project%20for%20Burnside%20Digital%2C%20and%20decided%20it%20was%20time%20to%20do%20some%20memory%20profiling%20to%20make%20sure%20that%20I%20didn%27t%20have%20any%20leaks.%C2%A0I%20ran%20the%20program%20with%20the%20%27Leaks%27%20tool%20of%20instruments%2C%20and%20as%20I%20was%20watching%20the%20Live"></a></li><li style="heigth:32px;width:32px"><a title="Delicious" class="option1_32" style="background-position:-32px 0px" rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;title=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis&amp;notes=I%20was%20recently%20working%20on%20an%20internal%20project%20for%20Burnside%20Digital%2C%20and%20decided%20it%20was%20time%20to%20do%20some%20memory%20profiling%20to%20make%20sure%20that%20I%20didn%27t%20have%20any%20leaks.%C2%A0I%20ran%20the%20program%20with%20the%20%27Leaks%27%20tool%20of%20instruments%2C%20and%20as%20I%20was%20watching%20the%20Live"></a></li><li style="heigth:32px;width:32px"><a title="Digg" class="option1_32" style="background-position:-64px 0px" rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;title=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis&amp;bodytext=I%20was%20recently%20working%20on%20an%20internal%20project%20for%20Burnside%20Digital%2C%20and%20decided%20it%20was%20time%20to%20do%20some%20memory%20profiling%20to%20make%20sure%20that%20I%20didn%27t%20have%20any%20leaks.%C2%A0I%20ran%20the%20program%20with%20the%20%27Leaks%27%20tool%20of%20instruments%2C%20and%20as%20I%20was%20watching%20the%20Live"></a></li><li style="heigth:32px;width:32px"><a title="Reddit" class="option1_32" style="background-position:-128px -32px" rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;title=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis"></a></li><li style="heigth:32px;width:32px"><a title="StumbleUpon" class="option1_32" style="background-position:-224px -32px" rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&title=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis"></a></li><li style="heigth:32px;width:32px"><a title="Google Bookmarks" class="option1_32" style="background-position:-192px 0px" rel="nofollow" target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;title=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis&amp;annotation=I%20was%20recently%20working%20on%20an%20internal%20project%20for%20Burnside%20Digital%2C%20and%20decided%20it%20was%20time%20to%20do%20some%20memory%20profiling%20to%20make%20sure%20that%20I%20didn%27t%20have%20any%20leaks.%C2%A0I%20ran%20the%20program%20with%20the%20%27Leaks%27%20tool%20of%20instruments%2C%20and%20as%20I%20was%20watching%20the%20Live"></a></li><li style="heigth:32px;width:32px"><a title="HackerNews" class="option1_32" style="background-position:-256px 0px" rel="nofollow" target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;t=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis"></a></li><li style="heigth:32px;width:32px"><a title="MSNReporter" class="option1_32" style="background-position:-352px 0px" rel="nofollow" target="_blank" href="http://reporter.es.msn.com/?fn=contribute&amp;Title=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis&amp;URL=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;cat_id=6&amp;tag_id=31&amp;Remark=I%20was%20recently%20working%20on%20an%20internal%20project%20for%20Burnside%20Digital%2C%20and%20decided%20it%20was%20time%20to%20do%20some%20memory%20profiling%20to%20make%20sure%20that%20I%20didn%27t%20have%20any%20leaks.%C2%A0I%20ran%20the%20program%20with%20the%20%27Leaks%27%20tool%20of%20instruments%2C%20and%20as%20I%20was%20watching%20the%20Live"></a></li><li style="heigth:32px;width:32px"><a title="BlinkList" class="option1_32" style="background-position:0px 0px" rel="nofollow" target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;Title=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis"></a></li><li style="heigth:32px;width:32px"><a title="Sphinn" class="option1_32" style="background-position:-192px -32px" rel="nofollow" target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F"></a></li><li style="heigth:32px;width:32px"><a title="Posterous" class="option1_32" style="background-position:-64px -32px" rel="nofollow" target="_blank" href="http://posterous.com/share?linkto=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;title=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis&amp;selection=I%20was%20recently%20working%20on%20an%20internal%20project%20for%20Burnside%20Digital%2C%20and%20decided%20it%20was%20time%20to%20do%20some%20memory%20profiling%20to%20make%20sure%20that%20I%20didn%27t%20have%20any%20leaks.%C2%A0I%20ran%20the%20program%20with%20the%20%27Leaks%27%20tool%20of%20instruments%2C%20and%20as%20I%20was%20watching%20the%20Live"></a></li><li style="heigth:32px;width:32px"><a title="Tumblr" class="option1_32" style="background-position:-256px -32px" rel="nofollow" target="_blank" href="http://www.tumblr.com/share?v=3&amp;u=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;t=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis&amp;s=I%20was%20recently%20working%20on%20an%20internal%20project%20for%20Burnside%20Digital%2C%20and%20decided%20it%20was%20time%20to%20do%20some%20memory%20profiling%20to%20make%20sure%20that%20I%20didn%27t%20have%20any%20leaks.%C2%A0I%20ran%20the%20program%20with%20the%20%27Leaks%27%20tool%20of%20instruments%2C%20and%20as%20I%20was%20watching%20the%20Live"></a></li><li style="heigth:32px;width:32px"><a title="email" class="option1_32" style="background-position:-160px 0px" rel="nofollow" target="_blank" href="https://mail.google.com/mail/?view=cm&fs=1&to&su=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis&body=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&ui=2&tf=1&shva=1"></a></li><li style="heigth:32px;width:32px"><a title="Google Reader" class="option1_32" style="background-position:-224px 0px" rel="nofollow" target="_blank" href="http://www.google.com/reader/link?url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;title=Debugging%20a%20memory%20increase%2C%20using%20Generational%20Analysis&amp;srcURL=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F11%2F19%2Fdebugging-a-memory-increase-using-generational-analysis%2F&amp;srcTitle=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials"></a></li><li style="heigth:32px;width:32px"><a class="option1_32" style="cursor:pointer;background-position:-128px 0px" rel="nofollow" title="Add to favorites - doesn't work in Chrome"  onClick="javascript:AddToFavorites();"></a></li><li style="heigth:32px;width:32px"><a style="cursor:poainter" rel="nofollow"   onMouseOver="more(this,'post-4556')"><img style='margin-top:9px' src='/wp-content/plugins/sociable/images/more.png'></a></li></ul>			

			</div>        

		  <a style="cursor:pointer" onclick="hide_sociable('post-4556',true)" class="close">

		  <img onclick="hide_sociable('post-4556',true)" title="close" src="/wp-content/plugins/sociable/images/closelabel.png">

		  </a>

		</div>

	</div> 

  </div></div><div class='sociable' style='float:none'><ul class='clearfix'><li id="Twitter_Counter"><a href="https://twitter.com/share" data-text="Debugging a memory increase, using Generational Analysis - http://icodeblog.com/2013/11/19/debugging-a-memory-increase-using-generational-analysis/" data-url="http://icodeblog.com/2013/11/19/debugging-a-memory-increase-using-generational-analysis/" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></li><li id="Facebook_Counter"><iframe src="http://www.facebook.com/plugins/like.php?href=http://icodeblog.com/2013/11/19/debugging-a-memory-increase-using-generational-analysis/&send=false&layout=button_count&show_faces=false&action=like&colorscheme=light&font" scrolling="no" frameborder="0" style="border:none; overflow:hidden;height:32px;width:100px" allowTransparency="true"></iframe></li><li id="Google_p"><g:plusone annotation="bubble" href="/2013/11/19/debugging-a-memory-increase-using-generational-analysis/" size="medium"></g:plusone></li><li id="LinkedIn_Counter"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="http://icodeblog.com/2013/11/19/debugging-a-memory-increase-using-generational-analysis/" data-counter="right"></script></li></ul></div><!-- End Sociable -->]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2013/11/19/debugging-a-memory-increase-using-generational-analysis/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>DICE+, rocketships and a giveaway.</title>
		<link>http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/</link>
		<comments>http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/#comments</comments>
		<pubDate>Sat, 06 Jul 2013 00:18:39 +0000</pubDate>
		<dc:creator><![CDATA[ebennett]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Dice+]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[rocketship]]></category>
		<category><![CDATA[space]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=4414</guid>
		<description><![CDATA[<a href="/wp-content/uploads/2013/07/screenShot.jpg"></a>
I received my <a title="DICE+" href="http://developers.dicepl.us" target="_blank">DICE+</a> developer kit a couple weeks ago and was excited to get to testing. What is DICE+? DICE+ is a bluetooth connected, smart, 6 sided die that is made out of materials safe to roll directly on your devices. It has a 20hr battery which powers a bunch of cool sensors like accelerometers, magnetic field sensor, touch sensitive faces, and a few more. The built in anti-cheat protection makes sure each roll is  ...]]></description>
				<content:encoded><![CDATA[<p style="text-align: center"><img class="alignleft size-medium wp-image-4469" alt="Dice+Image" src="/wp-content/uploads/2013/07/Dice+Image-300x300.jpg" width="300" height="300" /><a href="/wp-content/uploads/2013/07/screenShot.jpg"><img class="alignleft size-medium wp-image-4529" alt="screenShot" src="/wp-content/uploads/2013/07/screenShot-225x300.jpg" width="225" height="300" /></a></p>
<p>I received my <a title="DICE+" href="http://developers.dicepl.us" target="_blank">DICE+</a> developer kit a couple weeks ago and was excited to get to testing. What is DICE+? DICE+ is a bluetooth connected, smart, 6 sided die that is made out of materials safe to roll directly on your devices. It has a 20hr battery which powers a bunch of cool sensors like accelerometers, magnetic field sensor, touch sensitive faces, and a few more. The built in anti-cheat protection makes sure each roll is fair, and each face can display a wide range of colors due to the red, green and blue LEDs backlighting every side. Balanced to match any standard 6 sided die performance, the DICE+ brings back some of the tactile fun of playing games on digital devices. Although not quite out on the market as of this writing, developers can download the SDK, order kits and start developing. The developers over at DICE+ have also set aside a kit to give away to one of the readers of this post. The first 6 readers who reply to this post and correctly lists all sensors available, will be entered in the drawing. A DICE+ will then be rolled, a winner selected from those replies and sent one of the DICE+ developer kits. Now that I have had some fun, I thought I would share, and show how easy it was to use.</p>
<p>In the following tutorial, I have designed a simple 2 player game in which you are trying to be the first player to get your ship into space. Each player takes a turn rolling the die, the first player to reach 25 is the winner. With the addition of some simple UIView animations to animate our player ships and space background, the race to space can begin. Link to project file and assets are at the end of this post.</p>
<p>First lets create a new, single view, portrait oriented project for iPad called &#8216;RaceToSpace&#8217; using ARC (Automatic Reference Counting).  After downloading the DICE+ SDK from the website, drag and drop the framework into your project, add the &#8216;CoreBluetooth&#8217;, and QuartzCore frameworks. For DICE+, You will also have to add &#8216;-all_load&#8217; to your projects build settings, under other linker commands. In Interface Builder, add a UIImageView to your view, setting its size and origin to the following x=0, y=-1024, width=768 and height=2048. Press your editors double column view button, and while holding the control button, left mouse click the newly added UIImageView and link to your .h file creating an IBOutlet reference called &#8216;spaceBackground&#8217;. Add a Play button to start the game, a label at the bottom to show bluetooth connection info and turn status, and 2 labels at the top for displaying player scores. Link all of these to your .h file as you did with the space background UIImageView, using these corresponding names; playButton, status, player1Score, player2Score. You will also need to right click on the PLAYBUTTON, and link the &#8216;touch up inside&#8217; action onto your ViewController.m file and name it &#8216;Play&#8217;. Now that the basic building blocks are setup, we can get to configuring the software for use with your die.</p>
<p>In your ViewController .h, add the following code to match.</p>
<div class="wp_syntax">
<pre><span style="color: #800000"> 
#impor</span>t &lt;UIKit/UIKit.h&gt;
<span style="color: #800000">#import</span> &lt;DicePlus/DicePlus.h&gt;
<span style="color: #800000">#import</span> "Player.h"

<span style="color: #800000">@interface</span> ViewController : UIViewController <span style="color: #000080">&lt;DPDiceManagerDelegate&gt;</span>
{
    <span style="color: #000080">DPDiceManager</span>* diceManager;
    <span style="color: #000080">DPDie</span>* availableDie;
    <span style="color: #000080">DPDie</span>* connectedDie;
}
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UILabel</span> *player1Score;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UILabel</span> *player2Score;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UIImageView</span> *spaceBackground;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UILabel</span> *status;
<span style="color: #993300">@property</span> (nonatomic, retain) <span style="color: #000080">NSArray</span> *players;
<span style="color: #993300">@property</span> (nonatomic, retain) <span style="color: #000080">Player</span> *currentPlayer;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UIButton</span> *play;

@end</pre>
</div>
<p>In your ViewController.m, add the following code to your viewDidLoad method. This initializes the dice manager, sets the DEV KEY with the <b>[diceManager startScanning]</b> command, and starts scanning for available devices. Also add the #define MaxPoints 25. This defines the winning score.</p>
<div class="wp_syntax">
<pre><span style="color: #660000"> 
#define MaxPoints 25</span>

<span style="color: #993300">@implementation</span> ViewController

- (<span style="color: #993300">void</span>)viewDidLoad
{
    [super viewDidLoad];
<span style="color: #008000">    // Do any additional setup after loading the view, typically from a nib.
</span>
    if (connectedDie != nil) {
        return;
    }
    availableDie = nil;
    diceManager = [DPDiceManager sharedDiceManager];
    diceManager.delegate = self;

<span style="color: #008000">    //DICE+ generic development key.
</span>    uint8_t key[8] = {0x83, 0xed, 0x60, 0x0e, 0x5d, 0x31, 0x8f, 0xe7};
    [diceManager setKey:key];

    <span style="color: #008000">//Start scanning for an available DICE+</span>.
    [diceManager startScan];
    self.status.text = @"Searching for DICE+...";
}</pre>
</div>
<p>If you notice the error pertaining to the #import Player.h and the player object, we will be adding that in a moment so you can ignore that for now. We do need to add some delegate calls so we can be notified of a DICE+ connection, and some to receive results when the die is rolled. I will also explain in detail the contained code when we walk thru the functionality of the game.</p>
<div class="wp_syntax">
<pre> 
- (<span style="color: #993300">void</span>)die:(<span style="color: #000080">DPDie</span> *)die didRoll:(<span style="color: #000080">DPRoll</span> *)roll error:(<span style="color: #000080">NSError</span> *)error
{
    <span style="color: #008000">//Roll was valid</span>
    if (roll.flags == <span style="color: #993366">DPRollFlagOK</span>) {
        <span style="color: #008000">//Stop roll updates just to make sure wrong player doesnt mistakenly roll DICE+.</span>
        [connectedDie stopRollUpdates];
        <span style="color: #008000">//Convert roll result (1-6) to binary mask equivalent</span>
        int mask = 1 &lt;&lt; (roll.result-1);
<span style="color: #008000">        //Blink the top face green showing roll result. DICE+ uses a binary mask for determinning which face, or faces to light.
</span>        [connectedDie startBlinkAnimationWithMask:mask priority:0 r:0 g:255 b:0 onPeriod:100 cyclePeriod:50 blinkCount:5];
        <span style="color: #008000">//Move player ship</span>
        [self moveCurrentPlayer:roll.result];

    } else if (roll.flags == <span style="color: #993366">DPRollFlagTilt</span>) {
<span style="color: #008000">        //DICE+ roll error
</span>        self.status.text = @"Roll Tilted";
<span style="color: #008000">        //Blink DICE+ faces red to indicate a roll error occured.
</span>        [connectedDie startBlinkAnimationWithMask:63
                                         priority:1
                                                r:255
                                                g:0
                                                b:0
                                         onPeriod:100
                                      cyclePeriod:200
                                       blinkCount:4];
    } else if (roll.flags == <span style="color: #993366">DPRollFlagTooShort</span>) {
<span style="color: #008000">        //DICE+ roll error
</span>        self.status.text = @"Roll too short";
<span style="color: #008000">        //Blink dice plus faces red to indicate a roll error occured.
</span>        [connectedDie startBlinkAnimationWithMask:63
                                         priority:1
                                                r:255
                                                g:0
                                                b:0
                                         onPeriod:100
                                      cyclePeriod:200
                                       blinkCount:4];
    }
}

#pragma mark - DPDiceManagerDelegate methods
- (<span style="color: #993300">void</span>)centralManagerDidUpdateState:(<span style="color: #000080">CBCentralManagerState</span>)state
{
<span style="color: #008000">    // See CBCentralManagerDelegate documentation for info about CBCentralManager state changes
</span>}

- (<span style="color: #993300">void</span>)diceManagerStoppedScan:(<span style="color: #000080">DPDiceManager</span> *)manager
{
<span style="color: #008000">    //Scanning has stopped, restart scan if no available die was found.
</span>    if (availableDie == nil) {
        [diceManager startScan];
        self.status.text = @"Searching for DICE+...";
    }
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager didDiscoverDie:(<span style="color: #000080">DPDie</span> *)die
{
<span style="color: #008000">    //A DICE+ die was found, not connected yet.
</span>    availableDie = die;
    availableDie.delegate = (id)self;

    [diceManager stopScan];
<span style="color: #008000">    //Attempt to connect to available DICE+ found.
</span>    [diceManager connectDie:availableDie];

    self.status.text = @"Connecting DICE+...";
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager didConnectDie:(<span style="color: #000080">DPDie</span> *)die
{
<span style="color: #008000">    //Available DICE+ connected and is ready for play.
</span>    availableDie = nil;
    connectedDie = die;
    connectedDie.delegate = (id)self;
    self.status.text = @"Press play to begin.";
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager failedConnectingDie:(<span style="color: #000080">DPDie</span> *)die error:(<span style="color: #000080">NSError</span> *)error
{
<span style="color: #008000">    //DICE+ failed connection attempt.
</span>    availableDie = nil;
    connectedDie = nil;
    self.status.text = @"Connection failed... Searching...";

    [diceManager startScan];
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager didDisconnectDie:(<span style="color: #000080">DPDie</span> *)die error:(<span style="color: #000080">NSError</span> *)error
{
<span style="color: #008000">    //DICE+ disconnected
</span>    availableDie = nil;
    connectedDie = nil;
    self.status.text = @"Die disconnected... Searching...";

    [diceManager startScan];
}

- (<span style="color: #993300">void</span>)dieFailedAuthorization:(<span style="color: #000080">DPDie</span> *)die error:(<span style="color: #000080">NSError</span> *)error
{
<span style="color: #008000">    //DICE+ authorization failed.
</span>    self.status.text = @"Failed authorization";
}</pre>
</div>
<p>The DICE+ is well documented and there are quite a few delegate methods that can be used depending on which sensor you issue a startUpdate too.</p>
<p>We&#8217;ll go back to the functions of the game a little later on in the post, for now lets look at whats happening when connecting to the die.</p>
<p>After the app has started scanning for an active die and one has been found, the dice manager delegate , didDiscoverDie, will be called and the scanning is stopped using <b>[diceManager stopScan]</b>. Since we don&#8217;t know that we can successfully connect to the die, only that one is available, we store the returned found die as availableDie, then attempt a connection with it. If no available dice were found and the scanner times out (after 12 seconds), diceManagerStoppedScan: will get called. In our example we simply restart the scanning process and scan again.</p>
<p>Upon a successfull connection, dice manager didConnectDie delegate method is called. Since we want to differentiate between an available die and our successfully connected die, connectedDie is assigned and used for the rest of the games life cycle, and availableDie is nilled out. If for some reason there is an issue connecting to the available die, &#8216;failedConnectingDie:&#8217; is called. If a die is connected and looses that connection for some reason, the diceManager &#8216;didDisconnectDie:&#8217; is called. In this example a scan is started again to try and regain a connection.</p>
<p>Once we have a connected die, it is easy to start the various sensor updates and listen for their delegate calls. For this game, we will only worry about <b>[connectedDie startRollUpdates]</b>, <b>[connectedDie stopRollUpdates]</b>, and the corresponding delegate methods to receive the roll response once a valid roll is done.</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">void</span>)die:(<span style="color: #000080">DPDie</span> *)die didRoll:(<span style="color: #000080">DPRoll</span> *)roll error:(<span style="color: #000080">NSError</span> *)error</pre>
</div>
<p>The value of the roll is returned in roll.result with roll state in roll.flag that gives information about the roll itself. <span style="color: #993366">DPRollFlagOK</span> is returned with a valid roll, <span style="color: #993366">DPRollFlagTilt</span> is returned if the die has landed on a tilt, and <span style="color: #993366">DPRollFlagTooShort</span> if not enough time was taken to make the roll. These flags are part of the anti cheat error checking done within the die.</p>
<p>As we add the functionality of the game, you will also see how easy it is to change and animate the LEDs for each face once a roll is completed, or for any other reason you may need.</p>
<p>For the actual gameplay we will be adding 6 new methods but first we need to create a player object to represent each of our 2 players. Right click on the RaceToSpace folder in the left hand, project navigator pane and select new file. Create a new subclass of NSObject and name it Player.</p>
<p>Add the following to the Player.h,</p>
<div class="wp_syntax">
<pre><span style="color: #993300">@interface</span> Player : <span style="color: #000080">NSObject</span>

<span style="color: #993300">@property</span>(nonatomic, retain) <span style="color: #000080">UIImage</span> *shipImage;
<span style="color: #993300">@property</span>(nonatomic) <span style="color: #000080">NSInteger</span> score;
<span style="color: #993300">@property</span>(nonatomic) <span style="color: #000080">NSInteger</span> playerNumber;

- (<span style="color: #993300">id</span>)initWithImage:(<span style="color: #000080">UIImage</span> *)shipImage;

@end</pre>
</div>
<p>and this to your Player.m,</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">id</span>)initWithImage:(<span style="color: #000080">UIImage</span> *)shipImage;
{
    self = [super init];
    if (self) {
<span style="color: #008000">        // Initialization code
</span>        self.shipImage = shipImage;
        self.score = 0;
    }
    return self;
}</pre>
</div>
<p>Now we need to create the 2 players, do this at the beginning of your viewDidLoad, just after the call to super. Each player is created and assigned a player number, a UIImageView is also created to display the players ship, placed at their start positions on the screen and added to the view. By setting the tag of each of these UIImageViews to the players number, we can be sure to move the correct ship for the player. Initialize our player reference NSArray with both of our players..</p>
<div class="wp_syntax">
<pre> 
    [super viewDidLoad];
<span style="color: #008000">    // Do any additional setup after loading the view, typically from a nib.
</span>    
<span style="color: #008000">    //Setup Player 1
</span>    <span style="color: #000080">Player</span> *player1 = [[Player alloc] initWithImage:[UIImage imageNamed:@"rocketShip1"]];
    player1.playerNumber = 1;
    UIImageView *player1ship = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64, 113)];
    player1ship.contentMode = UIViewContentModeCenter;
    player1ship.image = player1.shipImage;
    player1ship.center = CGPointMake(192, 928);
    player1ship.tag = player1.playerNumber;
    [self.view addSubview:player1ship];

<span style="color: #008000">    //Setup Player 2
</span>    <span style="color: #000080">Player</span> *player2 = [[Player alloc] initWithImage:[UIImage imageNamed:@"rocketShip2"]];
    player2.playerNumber = 2;
    UIImageView *player2ship = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64, 113)];
    player2ship.contentMode = UIViewContentModeCenter;
    player2ship.image = player2.shipImage;
    player2ship.center = CGPointMake(576, 928);
    player2ship.tag = player2.playerNumber;
    [self.view addSubview:player2ship];</pre>
</div>
<p>Add some code to our Play button action and add these remaining methods to you ViewController.m and we will take a quick walk thru of the game.</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">IBAction</span>)play:(<span style="color: #000080">id</span>)sender
{
<span style="color: #008000">    //Rest players score to 0 in case this is a <span style="color: #000080">replay.
</span></span>    self.play.hidden = YES;
    [self setupPlayer];
}

- (<span style="color: #993300">void</span>)setupPlayer
{
    if (!self.currentPlayer){
<span style="color: #008000">        //Its a new game, make current player, player 1.
</span>        self.currentPlayer = [self.players objectAtIndex:0];
    } else {
<span style="color: #008000">            //Switch between players
</span>            if (self.currentPlayer.playerNumber == 1){
<span style="color: #008000">                //Make current player, player 2.
</span>                self.currentPlayer = [self.players objectAtIndex:1];
            } else {
<span style="color: #008000">                //Make current player, player 1.
</span>                self.currentPlayer = [self.players objectAtIndex:0];
            }
        }
    self.status.text = [NSString stringWithFormat:@"Player %i's turn", self.currentPlayer.playerNumber];

<span style="color: #008000">    //Start DICE+ roll updates for current player.
</span>    [connectedDie startRollUpdates];
}

- (<span style="color: #993300">void</span>)prepareForNewGame
{
<span style="color: #008000">    //Set player scores to 0 and reset ships to start position.
</span>    for (Player *p in self.players){
        p.score = 0;
        UIImageView *playerShip = (UIImageView *)[self.view viewWithTag:p.playerNumber];
        playerShip.center = CGPointMake(playerShip.center.x, 928);
    }

<span style="color: #008000">    //Reset some labels
</span>    self.play.hidden = NO;
    self.player1Score.text = @"0 points";
    self.player2Score.text = @"0 points";
    self.status.text = @"Press play to begin.";

<span style="color: #008000">    //Animate background back to start position
</span>    [UIView animateWithDuration:.25 animations:^{
        self.spaceBackground.center = CGPointMake(384, 0);
    }];

<span style="color: #008000">    //Set current player to nil so new game will start with player 1.
</span>    self.currentPlayer = nil;
}

- (<span style="color: #993300">BOOL</span>)currentPlayerIsWinner
{
<span style="color: #008000">    //check if current player has matched, or exceeded max points
</span>    if (self.currentPlayer.score &gt;= MaxPoints){
        return YES;
    }
    return NO;
}

- (<span style="color: #993300">void</span>)moveCurrentPlayer:(<span style="color: #000080">NSInteger</span>)rollValue
{
<span style="color: #008000">    //Get UIImageView for players ship and animate p the screen.
</span>    UIImageView *playerShip = (UIImageView *)[self.view viewWithTag:self.currentPlayer.playerNumber];

<span style="color: #008000">    //Calculate appropriate distance to travel based on MaxPoints, so winner is always near top of screen.
</span>    int offset = (1024 - rintf(1024/6))/MaxPoints;
    int distance = rollValue * offset;
    self.currentPlayer.score = self.currentPlayer.score + rollValue;

    if ([self currentPlayerIsWinner]) {
<span style="color: #008000">        //Current player has won. Do something.
</span>        NSString *winnerText = [NSString stringWithFormat:@"Congratulations player %i, you are the Winner!", self.currentPlayer.playerNumber];
        UIAlertView *winnerNotify = [[UIAlertView alloc] initWithTitle:@"WINNER!!" message:winnerText delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [winnerNotify show];
        self.status.text = @"We have a WINNER!";

<span style="color: #008000">        //Fly the winning ship the rest of the way off the screen.
</span>        [UIView animateWithDuration:1 animations:^{
            playerShip.center = CGPointMake(playerShip.center.x, -200);
        }];
        return;
    } else {
        [UIView animateWithDuration:1 animations:^{
            playerShip.center = CGPointMake(playerShip.center.x, playerShip.center.y - distance);
        }];
        if (self.currentPlayer.playerNumber == 2){
            self.player2Score.text = [NSString stringWithFormat:@"%i points", self.currentPlayer.score];
            [self slideBackground:distance];
        } else {
            self.player1Score.text = [NSString stringWithFormat:@"%i points", self.currentPlayer.score];
            [self setupPlayer];
        }
    }
}

- (<span style="color: #993300">void</span>)slideBackground:(<span style="color: #000080">NSInteger</span>)distance
{
<span style="color: #008000">    //Check if background is able to scroll any further, if so scroll up distace value.
</span>    if (self.spaceBackground.center.y + distance &lt; 1024){
        [UIView animateWithDuration:3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.spaceBackground.center = CGPointMake(384, self.spaceBackground.center.y + distance);
        } completion:^(BOOL finished) {
<span style="color: #008000">            //Setup next player when animation is done.
</span>            [self setupPlayer];
        }];
    }
}</pre>
</div>
<p>When the play button is pressed and the <b>&#8211; (IBAction)play:(id)sender</b> callback is called, the play button is hidden and <b>[self setupPlayer]</b> is called. SetupPlayer, checks to see if self.currentPlayer uninitialized, if so then it represents a new game and currentPlayer is assigned as Player1 from index 0 of the Players reference array. We set the text of our connection status label to state that it is player 1&#8217;s turn and the DICE+ roll updates are started with <b>[connectedDie startRollUpdates]</b>; The game is now waiting for player 1 to roll. Once a valid roll is made, the <b>die: didRoll:</b> delegate method is called. With a successful roll.flag of DPRollFlagOK a few things happen. Dependent on the value of roll.result, an int called mask is set to a specific value. This mask value is how we tell the DICE+ which face or faces to light up.</p>
<p>&nbsp;</p>
<p>A quick explanation of the  mask value. If you think of a 6 bit binary number, adding each decimal value of the bits (or faces) you want lit up, this total number is the mask. For example if I wanted the number 2 face to light,</p>
<p>1    2    3    4    5    6  (face)</p>
<p>1    2    4    8    16  32  (decimal value)</p>
<p>0    1    0    0    0    0  (binary mask)</p>
<p>Number for the mask would be 2.</p>
<p>If you wanted faces 1, 2 and 3 to light up, the mask would be,</p>
<p>1    2    3    4    5    6  (face)</p>
<p>1    2    4    8    16  32  (decimal value)</p>
<p>1    1    1     0    0    0  (binary mask)</p>
<p>Number for mask would be 6.</p>
<p>All faces would be represented by the number 63.</p>
<p>&nbsp;</p>
<p>We can pass this mask, as well as color and various other info to the die in a couple of different methods used to blink and fade the lights on and off. In our game, when a roll is invalid (either tilted or too short), an animation is used to blink all the faces red for a short time. Upon a valid roll, the face of the rolled value is blinked green.</p>
<p>After a successful roll, the roll updates of the die are stopped, this may not be necessary but may stop any accidental rolls and turn changes. <b>[self moveCurrentPlayer:roll.result]</b> is then called, passing along the rolled die value. This value is used in moveCurrentPlayer to move the current players ship up the screen (players UIImageView is found in the view by its tag), added to their current score and checks to see if the current player is the winner <b>[self currentPlayerIsWinner]</b> and returns a TRUE/FALSE. If the current player is not the winner, the game continues to the next step. If this is player2, then the background image is slid down the screen an appropriate amount in <b>[self slideBackground:roll.result]</b> using a simple UIView animation. Whether the background needed sliding or not, the next step is <b>[self setupPlayer]</b>.</p>
<p><b>[self setupPlayer]</b> determines that the currentPlayer is valid, checks the player&#8217;s number of the current player, and switches current player to the other player, roll updates are started once again and the next player can take their turn. In <b>[self moveCurrentPlayer]</b> once a player reaches, or passes, 25 (as defined at the top of ViewController.m in MaxPoints) that triggers the winning phase. One slight addition to add to our game is to show a UIAlertView when a player wins and inform us when it is dismissed so we can reset the game.</p>
<p>Add to your ViewController.h so we can know when the user dismisses the winning text and delegate call for the alertView,</p>
<div class="wp_syntax">
<pre>@interface ViewController : UIViewController &lt;DPDiceManagerDelegate, <span style="color: #0000ff">UIAlertViewDelegate</span>&gt;</pre>
</div>
<p>and the following in your ViewController.m so we know when it is dismissed.</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">void</span>)alertView:(<span style="color: #000080">UIAlertView</span> *)alertView didDismissWithButtonIndex:(<span style="color: #000080">NSInteger</span>)buttonIndex
{
<span style="color: #008000">    //Once cancel is pressed on the alertview, prepare for new game.
</span>    [self prepareForNewGame];
}</pre>
</div>
<p>On a winning score the UIAlertView is displayed, status text is updated and the winning ship is flown the rest of the way of the screen. When the player dismisses the UIAlertView popup, <b>[self prepareForNewGame]</b> is called. Within that method, variables are reset, ships are set back to their starting positions and currentPlayer is set to nil. With a press of the Play button once again, the game play can start again.</p>
<p>I realize a lot more could be added, more in-depth animations could be done and special instances such as rolling the same number twice in a row to initiate special rules but since this was more about attaching and using the DICE+, I will leave those upgrades and additions to you. Hope you enjoyed this tutorial, I have enjoyed getting to test out this new product and look forward to what may come of it. Thanks.</p>
<p>Here is the link to the <a title="Race to Space image files." href="/wp-content/uploads/2013/07/RaceToSpaceAssets.zip">images</a> used in the game, and here is a <a title="Race To Space" href="https://github.com/B-Sides/RaceToSpace" target="_blank">link</a> to the GitHub repository. In order to ensure the latest SDK, you will need to <a title="Developer link" href="http://developers.dicepl.us" target="_blank">download the DICE+ SDK</a> (the version of the SDK depends on the firmware loaded on the Die) separately, and drag the DicePlus.framework file into the project.</p>
<!-- Start Sociable --><div class="sociable"><ul class='clearfix'></ul><div onMouseout="fixOnMouseOut(this,event,'post-4414')" id="sociable-post-4414" style="display:none;">   

    <div style="top: auto; left: auto; display: block;" id="sociable">



		<div class="popup">

			<div class="content">

				<ul><li style="heigth:32px;width:32px"><a title="Facebook" class="option1_32" style="background-position:-96px 0px" rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;t=DICE%2B%2C%20rocketships%20and%20a%20giveaway."></a></li><li style="heigth:32px;width:32px"><a title="Myspace" class="option1_32" style="background-position:0px -32px" rel="nofollow" target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;t=DICE%2B%2C%20rocketships%20and%20a%20giveaway."></a></li><li style="heigth:32px;width:32px"><a title="Twitter" class="option1_32" style="background-position:-288px -32px" rel="nofollow" target="_blank" href="http://twitter.com/intent/tweet?text=DICE%2B%2C%20rocketships%20and%20a%20giveaway.%20-%20http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F%20  SHARETAG"></a></li><li style="heigth:32px;width:32px"><a title="LinkedIn" class="option1_32" style="background-position:-288px 0px" rel="nofollow" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;title=DICE%2B%2C%20rocketships%20and%20a%20giveaway.&amp;source=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials&amp;summary=%0D%0AI%20received%20my%20DICE%2B%20developer%20kit%20a%20couple%20weeks%20ago%20and%20was%20excited%20to%20get%20to%20testing.%20What%20is%20DICE%2B%3F%20DICE%2B%20is%20a%20bluetooth%20connected%2C%20smart%2C%206%20sided%20die%20that%20is%20made%20out%20of%20materials%20safe%20to%20roll%20directly%20on%20your%20devices.%20It%20has%20a%2020hr%20battery%20whi"></a></li><li style="heigth:32px;width:32px"><a title="Delicious" class="option1_32" style="background-position:-32px 0px" rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;title=DICE%2B%2C%20rocketships%20and%20a%20giveaway.&amp;notes=%0D%0AI%20received%20my%20DICE%2B%20developer%20kit%20a%20couple%20weeks%20ago%20and%20was%20excited%20to%20get%20to%20testing.%20What%20is%20DICE%2B%3F%20DICE%2B%20is%20a%20bluetooth%20connected%2C%20smart%2C%206%20sided%20die%20that%20is%20made%20out%20of%20materials%20safe%20to%20roll%20directly%20on%20your%20devices.%20It%20has%20a%2020hr%20battery%20whi"></a></li><li style="heigth:32px;width:32px"><a title="Digg" class="option1_32" style="background-position:-64px 0px" rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;title=DICE%2B%2C%20rocketships%20and%20a%20giveaway.&amp;bodytext=%0D%0AI%20received%20my%20DICE%2B%20developer%20kit%20a%20couple%20weeks%20ago%20and%20was%20excited%20to%20get%20to%20testing.%20What%20is%20DICE%2B%3F%20DICE%2B%20is%20a%20bluetooth%20connected%2C%20smart%2C%206%20sided%20die%20that%20is%20made%20out%20of%20materials%20safe%20to%20roll%20directly%20on%20your%20devices.%20It%20has%20a%2020hr%20battery%20whi"></a></li><li style="heigth:32px;width:32px"><a title="Reddit" class="option1_32" style="background-position:-128px -32px" rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;title=DICE%2B%2C%20rocketships%20and%20a%20giveaway."></a></li><li style="heigth:32px;width:32px"><a title="StumbleUpon" class="option1_32" style="background-position:-224px -32px" rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&title=DICE%2B%2C%20rocketships%20and%20a%20giveaway."></a></li><li style="heigth:32px;width:32px"><a title="Google Bookmarks" class="option1_32" style="background-position:-192px 0px" rel="nofollow" target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;title=DICE%2B%2C%20rocketships%20and%20a%20giveaway.&amp;annotation=%0D%0AI%20received%20my%20DICE%2B%20developer%20kit%20a%20couple%20weeks%20ago%20and%20was%20excited%20to%20get%20to%20testing.%20What%20is%20DICE%2B%3F%20DICE%2B%20is%20a%20bluetooth%20connected%2C%20smart%2C%206%20sided%20die%20that%20is%20made%20out%20of%20materials%20safe%20to%20roll%20directly%20on%20your%20devices.%20It%20has%20a%2020hr%20battery%20whi"></a></li><li style="heigth:32px;width:32px"><a title="HackerNews" class="option1_32" style="background-position:-256px 0px" rel="nofollow" target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;t=DICE%2B%2C%20rocketships%20and%20a%20giveaway."></a></li><li style="heigth:32px;width:32px"><a title="MSNReporter" class="option1_32" style="background-position:-352px 0px" rel="nofollow" target="_blank" href="http://reporter.es.msn.com/?fn=contribute&amp;Title=DICE%2B%2C%20rocketships%20and%20a%20giveaway.&amp;URL=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;cat_id=6&amp;tag_id=31&amp;Remark=%0D%0AI%20received%20my%20DICE%2B%20developer%20kit%20a%20couple%20weeks%20ago%20and%20was%20excited%20to%20get%20to%20testing.%20What%20is%20DICE%2B%3F%20DICE%2B%20is%20a%20bluetooth%20connected%2C%20smart%2C%206%20sided%20die%20that%20is%20made%20out%20of%20materials%20safe%20to%20roll%20directly%20on%20your%20devices.%20It%20has%20a%2020hr%20battery%20whi"></a></li><li style="heigth:32px;width:32px"><a title="BlinkList" class="option1_32" style="background-position:0px 0px" rel="nofollow" target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;Title=DICE%2B%2C%20rocketships%20and%20a%20giveaway."></a></li><li style="heigth:32px;width:32px"><a title="Sphinn" class="option1_32" style="background-position:-192px -32px" rel="nofollow" target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F"></a></li><li style="heigth:32px;width:32px"><a title="Posterous" class="option1_32" style="background-position:-64px -32px" rel="nofollow" target="_blank" href="http://posterous.com/share?linkto=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;title=DICE%2B%2C%20rocketships%20and%20a%20giveaway.&amp;selection=%0D%0AI%20received%20my%20DICE%2B%20developer%20kit%20a%20couple%20weeks%20ago%20and%20was%20excited%20to%20get%20to%20testing.%20What%20is%20DICE%2B%3F%20DICE%2B%20is%20a%20bluetooth%20connected%2C%20smart%2C%206%20sided%20die%20that%20is%20made%20out%20of%20materials%20safe%20to%20roll%20directly%20on%20your%20devices.%20It%20has%20a%2020hr%20battery%20whi"></a></li><li style="heigth:32px;width:32px"><a title="Tumblr" class="option1_32" style="background-position:-256px -32px" rel="nofollow" target="_blank" href="http://www.tumblr.com/share?v=3&amp;u=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;t=DICE%2B%2C%20rocketships%20and%20a%20giveaway.&amp;s=%0D%0AI%20received%20my%20DICE%2B%20developer%20kit%20a%20couple%20weeks%20ago%20and%20was%20excited%20to%20get%20to%20testing.%20What%20is%20DICE%2B%3F%20DICE%2B%20is%20a%20bluetooth%20connected%2C%20smart%2C%206%20sided%20die%20that%20is%20made%20out%20of%20materials%20safe%20to%20roll%20directly%20on%20your%20devices.%20It%20has%20a%2020hr%20battery%20whi"></a></li><li style="heigth:32px;width:32px"><a title="email" class="option1_32" style="background-position:-160px 0px" rel="nofollow" target="_blank" href="https://mail.google.com/mail/?view=cm&fs=1&to&su=DICE%2B%2C%20rocketships%20and%20a%20giveaway.&body=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&ui=2&tf=1&shva=1"></a></li><li style="heigth:32px;width:32px"><a title="Google Reader" class="option1_32" style="background-position:-224px 0px" rel="nofollow" target="_blank" href="http://www.google.com/reader/link?url=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;title=DICE%2B%2C%20rocketships%20and%20a%20giveaway.&amp;srcURL=http%3A%2F%2Fwww.icodeblog.com%2F2013%2F07%2F06%2Fdice-rocketships-and-a-giveaway%2F&amp;srcTitle=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials"></a></li><li style="heigth:32px;width:32px"><a class="option1_32" style="cursor:pointer;background-position:-128px 0px" rel="nofollow" title="Add to favorites - doesn't work in Chrome"  onClick="javascript:AddToFavorites();"></a></li><li style="heigth:32px;width:32px"><a style="cursor:poainter" rel="nofollow"   onMouseOver="more(this,'post-4414')"><img style='margin-top:9px' src='/wp-content/plugins/sociable/images/more.png'></a></li></ul>			

			</div>        

		  <a style="cursor:pointer" onclick="hide_sociable('post-4414',true)" class="close">

		  <img onclick="hide_sociable('post-4414',true)" title="close" src="/wp-content/plugins/sociable/images/closelabel.png">

		  </a>

		</div>

	</div> 

  </div></div><div class='sociable' style='float:none'><ul class='clearfix'><li id="Twitter_Counter"><a href="https://twitter.com/share" data-text="DICE+, rocketships and a giveaway. - http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/" data-url="http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></li><li id="Facebook_Counter"><iframe src="http://www.facebook.com/plugins/like.php?href=http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/&send=false&layout=button_count&show_faces=false&action=like&colorscheme=light&font" scrolling="no" frameborder="0" style="border:none; overflow:hidden;height:32px;width:100px" allowTransparency="true"></iframe></li><li id="Google_p"><g:plusone annotation="bubble" href="/2013/07/06/dice-rocketships-and-a-giveaway/" size="medium"></g:plusone></li><li id="LinkedIn_Counter"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/" data-counter="right"></script></li></ul></div><!-- End Sociable -->]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Tutorial: Asynchronous HTTP Client Using NSOperationQueue</title>
		<link>http://icodeblog.com/2012/10/19/tutorial-asynchronous-http-client-using-nsoperationqueue/</link>
		<comments>http://icodeblog.com/2012/10/19/tutorial-asynchronous-http-client-using-nsoperationqueue/#comments</comments>
		<pubDate>Fri, 19 Oct 2012 09:01:12 +0000</pubDate>
		<dc:creator><![CDATA[dsklenar]]></dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=4235</guid>
		<description><![CDATA[Introduction
Recently here at ELC, we’ve been working on an app that requires a lot of server interaction, which has been a learning experience for managing threading, server load and connectivity. In order to keep the app performant and responsive while sending a large number of requests and aggregating a large set of data, our team had to intelligently manage and prioritize network interactions.
This is where <a title="NSOperationQueue documentation" href="http://developer.apple.com/library/ios/#documentation/cocoa/Reference/NSOperationQueue_class/Reference/Reference.html" target="_blank">NSOperationQueue</a> helps out. This class relies heavily on Grand Central Dispatch  ...]]></description>
				<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>Recently here at ELC, we’ve been working on an app that requires a lot of server interaction, which has been a learning experience for managing threading, server load and connectivity. In order to keep the app performant and responsive while sending a large number of requests and aggregating a large set of data, our team had to intelligently manage and prioritize network interactions.</p>
<p>This is where <a title="NSOperationQueue documentation" href="http://developer.apple.com/library/ios/#documentation/cocoa/Reference/NSOperationQueue_class/Reference/Reference.html" target="_blank">NSOperationQueue</a> helps out. This class relies heavily on Grand Central Dispatch (GCD) to execute NSOperations (in this case, HTTP requests and JSON serializations). These operations can be executed in various configurations, including concurrently and asynchronously.</p>
<p>In this tutorial, I’ll show you how to set up a block-based operation queue that takes advantage of NSBlockOperation, a concrete subclass of NSOperation. You can use this server client class to manage all interactions with your external server. To demonstrate this, our sample code will query Twitter for a set of search tags and return the results asynchronously. The sample code is available on <strong><a href="https://github.com/dsklen/QueuedHTTPClientSample" target="_blank">GitHub</a></strong>. Let’s get started.</p>
<p><strong>Server Client Setup<br />
</strong><br />
First, create a MediaServer class with an operation queue property. This server class is a singleton because we want to route all network requests through a single operation queue.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> MediaServer <span style="color: #002200;">:</span> <span style="color: #400080;">NSObject</span>
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>strong<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSOperationQueue</span> <span style="color: #002200;">*</span>operationQueue;
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sharedMediaServer;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>Our server singleton is instantiated as follows. Note that using <code>dispatch_once</code> takes advantage of GCD and is recommended by Apple for thread safety.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sharedMediaServer;
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">static</span> dispatch_once_t onceToken;
    <span style="color: #a61390;">static</span> <span style="color: #a61390;">id</span> sharedMediaServer <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
    dispatch_once<span style="color: #002200;">&#40;</span> <span style="color: #002200;">&amp;</span>amp;onceToken, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
        sharedMediaServer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self class<span style="color: #002200;">&#93;</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #a61390;">return</span> sharedMediaServer;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Next, in MediaServer’s init method, initialize the operation queue and set the concurrent operation count. The maxConcurrentOperationCount property can be changed later, too.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>init;
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> <span style="color: #002200;">&#40;</span> self <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span> <span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>        
        _operationQueue <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSOperationQueue</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
        _operationQueue.maxConcurrentOperationCount <span style="color: #002200;">=</span> <span style="color: #2400d9;">2</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p><strong>Search Tags Management<br />
</strong><br />
In the project files, you’ll notice SearchTagsViewController. I’ve set this up to handle adding, removing and editing Twitter search tags. You’ll find a pretty straightforward implementation using NSUserDefaults to persist your search tags. The main purpose of this view controller is to prepare a series of server requests.</p>
<p><strong>Server Calls Using NSBlockOperation<br />
</strong><br />
Now, we’re ready to start using our operation queue. For our example, we’ll be searching for tweets containing various keywords, so we only need one fetch method in our server class.</p>
<p>Note: because blocks are a bit syntactically difficult to read, it can be convenient to typedef assign a block’s input and return parameters. This also makes methods much more readable when passing in blocks. For our example, we are expecting an array of tweet objects, and we’ll check for errors in the HTTP request and JSON serialization. In MediaServer.h, add:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">typedef</span> <span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>FetchBlock<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>items, <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>Now, we’re ready to add our fetch tweets method. This method accepts a search string and a return block (FetchBlock). This method will create an NSBlockOperation instance using blockOperationWithBlock: and dispatch it to the Media Server’s dispatch queue. Within that block, we’ll asynchronously send an NSURLRequest, serialize the response and synchronously return the tweets using our FetchBlock. Let’s take a look at the code.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>fetchTweetsForSearch<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>searchString block<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>FetchBlock<span style="color: #002200;">&#41;</span>block;
<span style="color: #002200;">&#123;</span>
    NSBlockOperation <span style="color: #002200;">*</span>operation <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>NSBlockOperation blockOperationWithBlock<span style="color: #002200;">:^</span><span style="color: #002200;">&#123;</span>
&nbsp;
        <span style="color: #400080;">NSMutableArray</span> <span style="color: #002200;">*</span>tweetObjects <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableArray</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
        <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
        <span style="color: #400080;">NSHTTPURLResponse</span> <span style="color: #002200;">*</span>response <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
        <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>encodedSearchString <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>searchString stringWithURLEncoding<span style="color: #002200;">&#93;</span>;
        <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>URLString <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://search.twitter.com/search.json?q=%@&amp;amp;rpp=%i&amp;amp;include_entities=true&amp;amp;result_type=mixed&quot;</span>, encodedSearchString, SEARCH_RESULTS_PER_TAG<span style="color: #002200;">&#93;</span>;
        <span style="color: #400080;">NSURLRequest</span> <span style="color: #002200;">*</span>request <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURLRequest</span> requestWithURL<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> URLWithString<span style="color: #002200;">:</span>URLString<span style="color: #002200;">&#93;</span> cachePolicy<span style="color: #002200;">:</span>NSURLRequestReloadIgnoringLocalCacheData timeoutInterval<span style="color: #002200;">:</span>DEFAULT_TIMEOUT<span style="color: #002200;">&#93;</span>;
        <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURLConnection</span> sendSynchronousRequest<span style="color: #002200;">:</span>request returningResponse<span style="color: #002200;">:&amp;</span>amp;response error<span style="color: #002200;">:&amp;</span>amp;error<span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>JSON <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>NSJSONSerialization JSONObjectWithData<span style="color: #002200;">:</span>data options<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> error<span style="color: #002200;">:&amp;</span>amp;error<span style="color: #002200;">&#93;</span>;
        <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>tweets <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>JSON objectForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;results&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #11740a; font-style: italic;">// Serialize JSON response into lightweight Tweet objects for convenience.</span>
&nbsp;
        <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span> <span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>tweetDictionary <span style="color: #a61390;">in</span> tweets <span style="color: #002200;">&#41;</span>
        <span style="color: #002200;">&#123;</span>
            Tweet <span style="color: #002200;">*</span>tweet <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>Tweet alloc<span style="color: #002200;">&#93;</span> initWithJSON<span style="color: #002200;">:</span>tweetDictionary<span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#91;</span>tweetObjects addObject<span style="color: #002200;">:</span>tweet<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span>        
&nbsp;
        NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Search for '%@' returned %i results.&quot;</span>, searchString, <span style="color: #002200;">&#91;</span>tweetObjects count<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
        <span style="color: #11740a; font-style: italic;">// Return to the main queue once the request has been processed.</span>
&nbsp;
        <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSOperationQueue</span> mainQueue<span style="color: #002200;">&#93;</span> addOperationWithBlock<span style="color: #002200;">:^</span><span style="color: #002200;">&#123;</span>
&nbsp;
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> error <span style="color: #002200;">&#41;</span>
                block<span style="color: #002200;">&#40;</span> <span style="color: #a61390;">nil</span>, error <span style="color: #002200;">&#41;</span>;
            <span style="color: #a61390;">else</span>
                block<span style="color: #002200;">&#40;</span> tweetObjects, <span style="color: #a61390;">nil</span> <span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Optionally, set the operation priority. This is useful when flooding</span>
    <span style="color: #11740a; font-style: italic;">// the operation queue with different requests.</span>
&nbsp;
    <span style="color: #002200;">&#91;</span>operation setQueuePriority<span style="color: #002200;">:</span>NSOperationQueuePriorityVeryHigh<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>self.operationQueue addOperation<span style="color: #002200;">:</span>operation<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p><strong>Dispatching Tweet Searches<br />
</strong><br />
Let’s look at how we’ll use this server method. In TweetsViewController’s viewDidLoad: method, we’ll want to loop through our search tags and fetch each set of tweets. Because each operation is dispatched to our operation queue, we don’t have to worry about swamping the server or causing timeouts due to limited network bandwidth. To do so, in viewDidLoad:, add:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">MediaServer <span style="color: #002200;">*</span>server <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>MediaServer sharedMediaServer<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>tag <span style="color: #a61390;">in</span> self.tags<span style="color: #002200;">&#41;</span> 
    <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>server fetchTweetsForSearch<span style="color: #002200;">:</span>tag block<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>items, <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
&nbsp;
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> items <span style="color: #002200;">&amp;</span>amp;<span style="color: #002200;">&amp;</span>amp; error <span style="color: #002200;">==</span> <span style="color: #a61390;">nil</span> <span style="color: #002200;">&#41;</span>
            <span style="color: #002200;">&#123;</span>
                <span style="color: #002200;">&#91;</span>self.tweets addObjectsFromArray<span style="color: #002200;">:</span>items<span style="color: #002200;">&#93;</span>;
&nbsp;
                <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>sortDescriptorsArray <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithObject<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSSortDescriptor</span> sortDescriptorWithKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;createdAtDate&quot;</span> ascending<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#91;</span>self.tweets sortUsingDescriptors<span style="color: #002200;">:</span>sortDescriptorsArray<span style="color: #002200;">&#93;</span>;
&nbsp;
                <span style="color: #002200;">&#91;</span>self.tableView reloadData<span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#91;</span>self.activity stopAnimating<span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span>
        <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p><strong>Canceling Tweet Searches<br />
</strong><br />
In certain cases, you might want to cancel operations in your queue, for example, when the user navigates away from a view displaying content from several server requests. In this example, when the user taps the back ‘Tags’ button, we want to prevent the remaining search requests from going through. This is as easy as:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewDidDisappear<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>animated;
<span style="color: #002200;">&#123;</span>
    MediaServer <span style="color: #002200;">*</span>server <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>MediaServer sharedMediaServer<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>server operationQueue<span style="color: #002200;">&#93;</span> cancelAllOperations<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Note that this doesn’t immediately remove operations from the queue, instead it notifies the queue to abort the operation as soon as possible. If you need more specific control of which operations to keep running, NSOperationQueue also exposes an operations property to manually cancel specific operations.</p>
<p><strong>Concurrency</strong></p>
<p>The only thing fetchTweetsForSearch:block: does is create an operation and submit it to the queue, so it returns almost immediately. The main benefit of this approach is that all of the work within the block operation occurs on a background queue, leaving the main thread free and ensuring that the UI remains responsive. To confirm this is working properly, you can open up the Time Profiler in Instruments (an extremely useful tool for improving UX) and check which queue the block is executed on.</p>
<p><img alt="Profiled NSOperation" src="/wp-content/uploads/2012/10/NSOperation-Threading-Profiler.png" /></p>
<p>In the profiler, you’ll see that <code>initWithJSON:</code>, <code>JSONObjectWithData:options:error:</code> and sendSynchronousRequest:returningResponse:error: are all executed on a dispatched worker thread, not the main thread. That’s exactly what we want.</p>
<p><strong>Conclusion</strong></p>
<p>There you have it. As a developer, you’ll glean the most benefit from this server paradigm when sending out a large number of URL requests or when your user is on a slow network. If you do encounter situations where your queue is filling up with requests, remember that you can prioritize your operations, e.g.,</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>operation setQueuePriority<span style="color: #002200;">:</span>NSOperationQueuePriorityVeryHigh<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>Another benefit of this approach is the ability to return cached data using our FetchBlock, while updating from the server in the background. Look for more on that in a later blog post.</p>
<p>Happy iCoding!</p>
<p><strong><a title="Sample code" href="https://github.com/dsklen/QueuedHTTPClientSample" target="_blank">Source Code &#8211; GitHub</a></strong></p>
<!-- Start Sociable --><div class="sociable"><ul class='clearfix'></ul><div onMouseout="fixOnMouseOut(this,event,'post-4235')" id="sociable-post-4235" style="display:none;">   

    <div style="top: auto; left: auto; display: block;" id="sociable">



		<div class="popup">

			<div class="content">

				<ul><li style="heigth:32px;width:32px"><a title="Facebook" class="option1_32" style="background-position:-96px 0px" rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;t=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue"></a></li><li style="heigth:32px;width:32px"><a title="Myspace" class="option1_32" style="background-position:0px -32px" rel="nofollow" target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;t=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue"></a></li><li style="heigth:32px;width:32px"><a title="Twitter" class="option1_32" style="background-position:-288px -32px" rel="nofollow" target="_blank" href="http://twitter.com/intent/tweet?text=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue%20-%20http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F%20  SHARETAG"></a></li><li style="heigth:32px;width:32px"><a title="LinkedIn" class="option1_32" style="background-position:-288px 0px" rel="nofollow" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;title=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue&amp;source=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials&amp;summary=Introduction%0D%0A%0D%0ARecently%20here%20at%20ELC%2C%20we%E2%80%99ve%20been%20working%20on%20an%20app%20that%20requires%20a%20lot%20of%20server%20interaction%2C%20which%20has%20been%20a%20learning%20experience%20for%20managing%20threading%2C%20server%20load%20and%20connectivity.%20In%20order%20to%20keep%20the%20app%20performant%20and%20respons"></a></li><li style="heigth:32px;width:32px"><a title="Delicious" class="option1_32" style="background-position:-32px 0px" rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;title=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue&amp;notes=Introduction%0D%0A%0D%0ARecently%20here%20at%20ELC%2C%20we%E2%80%99ve%20been%20working%20on%20an%20app%20that%20requires%20a%20lot%20of%20server%20interaction%2C%20which%20has%20been%20a%20learning%20experience%20for%20managing%20threading%2C%20server%20load%20and%20connectivity.%20In%20order%20to%20keep%20the%20app%20performant%20and%20respons"></a></li><li style="heigth:32px;width:32px"><a title="Digg" class="option1_32" style="background-position:-64px 0px" rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;title=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue&amp;bodytext=Introduction%0D%0A%0D%0ARecently%20here%20at%20ELC%2C%20we%E2%80%99ve%20been%20working%20on%20an%20app%20that%20requires%20a%20lot%20of%20server%20interaction%2C%20which%20has%20been%20a%20learning%20experience%20for%20managing%20threading%2C%20server%20load%20and%20connectivity.%20In%20order%20to%20keep%20the%20app%20performant%20and%20respons"></a></li><li style="heigth:32px;width:32px"><a title="Reddit" class="option1_32" style="background-position:-128px -32px" rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;title=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue"></a></li><li style="heigth:32px;width:32px"><a title="StumbleUpon" class="option1_32" style="background-position:-224px -32px" rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&title=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue"></a></li><li style="heigth:32px;width:32px"><a title="Google Bookmarks" class="option1_32" style="background-position:-192px 0px" rel="nofollow" target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;title=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue&amp;annotation=Introduction%0D%0A%0D%0ARecently%20here%20at%20ELC%2C%20we%E2%80%99ve%20been%20working%20on%20an%20app%20that%20requires%20a%20lot%20of%20server%20interaction%2C%20which%20has%20been%20a%20learning%20experience%20for%20managing%20threading%2C%20server%20load%20and%20connectivity.%20In%20order%20to%20keep%20the%20app%20performant%20and%20respons"></a></li><li style="heigth:32px;width:32px"><a title="HackerNews" class="option1_32" style="background-position:-256px 0px" rel="nofollow" target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;t=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue"></a></li><li style="heigth:32px;width:32px"><a title="MSNReporter" class="option1_32" style="background-position:-352px 0px" rel="nofollow" target="_blank" href="http://reporter.es.msn.com/?fn=contribute&amp;Title=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue&amp;URL=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;cat_id=6&amp;tag_id=31&amp;Remark=Introduction%0D%0A%0D%0ARecently%20here%20at%20ELC%2C%20we%E2%80%99ve%20been%20working%20on%20an%20app%20that%20requires%20a%20lot%20of%20server%20interaction%2C%20which%20has%20been%20a%20learning%20experience%20for%20managing%20threading%2C%20server%20load%20and%20connectivity.%20In%20order%20to%20keep%20the%20app%20performant%20and%20respons"></a></li><li style="heigth:32px;width:32px"><a title="BlinkList" class="option1_32" style="background-position:0px 0px" rel="nofollow" target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;Title=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue"></a></li><li style="heigth:32px;width:32px"><a title="Sphinn" class="option1_32" style="background-position:-192px -32px" rel="nofollow" target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F"></a></li><li style="heigth:32px;width:32px"><a title="Posterous" class="option1_32" style="background-position:-64px -32px" rel="nofollow" target="_blank" href="http://posterous.com/share?linkto=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;title=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue&amp;selection=Introduction%0D%0A%0D%0ARecently%20here%20at%20ELC%2C%20we%E2%80%99ve%20been%20working%20on%20an%20app%20that%20requires%20a%20lot%20of%20server%20interaction%2C%20which%20has%20been%20a%20learning%20experience%20for%20managing%20threading%2C%20server%20load%20and%20connectivity.%20In%20order%20to%20keep%20the%20app%20performant%20and%20respons"></a></li><li style="heigth:32px;width:32px"><a title="Tumblr" class="option1_32" style="background-position:-256px -32px" rel="nofollow" target="_blank" href="http://www.tumblr.com/share?v=3&amp;u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;t=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue&amp;s=Introduction%0D%0A%0D%0ARecently%20here%20at%20ELC%2C%20we%E2%80%99ve%20been%20working%20on%20an%20app%20that%20requires%20a%20lot%20of%20server%20interaction%2C%20which%20has%20been%20a%20learning%20experience%20for%20managing%20threading%2C%20server%20load%20and%20connectivity.%20In%20order%20to%20keep%20the%20app%20performant%20and%20respons"></a></li><li style="heigth:32px;width:32px"><a title="email" class="option1_32" style="background-position:-160px 0px" rel="nofollow" target="_blank" href="https://mail.google.com/mail/?view=cm&fs=1&to&su=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue&body=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&ui=2&tf=1&shva=1"></a></li><li style="heigth:32px;width:32px"><a title="Google Reader" class="option1_32" style="background-position:-224px 0px" rel="nofollow" target="_blank" href="http://www.google.com/reader/link?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;title=Tutorial%3A%20Asynchronous%20HTTP%20Client%20Using%20NSOperationQueue&amp;srcURL=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F10%2F19%2Ftutorial-asynchronous-http-client-using-nsoperationqueue%2F&amp;srcTitle=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials"></a></li><li style="heigth:32px;width:32px"><a class="option1_32" style="cursor:pointer;background-position:-128px 0px" rel="nofollow" title="Add to favorites - doesn't work in Chrome"  onClick="javascript:AddToFavorites();"></a></li><li style="heigth:32px;width:32px"><a style="cursor:poainter" rel="nofollow"   onMouseOver="more(this,'post-4235')"><img style='margin-top:9px' src='/wp-content/plugins/sociable/images/more.png'></a></li></ul>			

			</div>        

		  <a style="cursor:pointer" onclick="hide_sociable('post-4235',true)" class="close">

		  <img onclick="hide_sociable('post-4235',true)" title="close" src="/wp-content/plugins/sociable/images/closelabel.png">

		  </a>

		</div>

	</div> 

  </div></div><div class='sociable' style='float:none'><ul class='clearfix'><li id="Twitter_Counter"><a href="https://twitter.com/share" data-text="Tutorial: Asynchronous HTTP Client Using NSOperationQueue - http://icodeblog.com/2012/10/19/tutorial-asynchronous-http-client-using-nsoperationqueue/" data-url="http://icodeblog.com/2012/10/19/tutorial-asynchronous-http-client-using-nsoperationqueue/" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></li><li id="Facebook_Counter"><iframe src="http://www.facebook.com/plugins/like.php?href=http://icodeblog.com/2012/10/19/tutorial-asynchronous-http-client-using-nsoperationqueue/&send=false&layout=button_count&show_faces=false&action=like&colorscheme=light&font" scrolling="no" frameborder="0" style="border:none; overflow:hidden;height:32px;width:100px" allowTransparency="true"></iframe></li><li id="Google_p"><g:plusone annotation="bubble" href="/2012/10/19/tutorial-asynchronous-http-client-using-nsoperationqueue/" size="medium"></g:plusone></li><li id="LinkedIn_Counter"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="http://icodeblog.com/2012/10/19/tutorial-asynchronous-http-client-using-nsoperationqueue/" data-counter="right"></script></li></ul></div><!-- End Sociable -->]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2012/10/19/tutorial-asynchronous-http-client-using-nsoperationqueue/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Adding an OpenGL ES view to your project using NinevehGL</title>
		<link>http://icodeblog.com/2012/09/07/3856/</link>
		<comments>http://icodeblog.com/2012/09/07/3856/#comments</comments>
		<pubDate>Fri, 07 Sep 2012 09:00:34 +0000</pubDate>
		<dc:creator><![CDATA[ebennett]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[3d]]></category>
		<category><![CDATA[Advanced]]></category>
		<category><![CDATA[gl]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[opengl es]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=3856</guid>
		<description><![CDATA[Recently I came across an openGL ES 2.0 engine that made setup, displaying and animating of 3D objects a breeze, called <a title="NinevehGL" href="http://nineveh.gl" target="_blank">NinevehGL</a>.  This 3D engine has many great features including a full multithreading environment, to keep the main run loop free during object rendering,  motion tweening, object groupings, custom lighting, materials and textures, custom shader support,  and native support for augmented reality, just to name a few. Another major benefit is the ability to import both wavefront  ...]]></description>
				<content:encoded><![CDATA[<p>Recently I came across an openGL ES 2.0 engine that made setup, displaying and animating of 3D objects a breeze, called <a title="NinevehGL" href="http://nineveh.gl" target="_blank">NinevehGL</a>.  This 3D engine has many great features including a full multithreading environment, to keep the main run loop free during object rendering,  motion tweening, object groupings, custom lighting, materials and textures, custom shader support,  and native support for augmented reality, just to name a few. Another major benefit is the ability to import both wavefront (.obj) and Collada (.dae) files. This framework is very easy to use, powerful,  and can be utilized in many different ways.</p>
<p><iframe src="http://player.vimeo.com/video/48964690" height="758" width="500" allowfullscreen="" frameborder="0"></iframe></p>
<p><a href="http://vimeo.com/48964690">IOS openGL rotating Earth using NinevehGL</a> from <a href="http://vimeo.com/user13362310">Erick Bennett</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
<p>In this tutorial I am going to show you how to easily, and effectively add an openGL ES 2.0 3D view into your project, and display a fully rendered, rotating 3D earth. The model assets are available <a title="openGLView assets" href="/wp-content/uploads/2012/09/openGLViewAssets.zip">here</a>, and include the object and texture. These assets are also available in the <a title="openGLview Project file." href="/wp-content/uploads/2012/09/openGLview.zip">project ZIP file</a>, available thru the link at the end of this tutorial.</p>
<p>Download and install the <a title="NinevehGL" href="http://nineveh.gl" target="_blank">NinevehGL framework</a>.</p>
<p>Since we want to add this view into an existing project and understand how the engine functions, lets create a new single-view project to start. Although <a title="NinevehGL" href="http://nineveh.gl" target="_blank">NinevehGL</a> can just as easily be setup thru interface builder, we will be adding this view programmatically. For this exercise, it does not matter if you select storyboard or XIB for the new project.</p>
<p>To begin with there are a few frameworks we will need to add. Do this by first selecting your projects main file in the project navigator pane. Make sure your projects target is selected, and under Build Phases click &#8216;Link Binaries with Libraries&#8217;. Use the + at the bottom of this display and add the <strong>QuartsCore </strong> and <strong>OpenGLES</strong> frameworks.</p>
<p><a href="/2012/09/07/3856/addframework/" rel="attachment wp-att-4107"><img class="aligncenter size-medium wp-image-4107" alt="" src="/wp-content/uploads/2012/09/addFramework-300x135.png" width="300" height="135" /></a></p>
<p>Next, using the &#8216;Add Other&#8217; button, navigate to your downloaded NinevehGL folder and import the <strong>NinevehGL.framework</strong>.</p>
<p><a href="/2012/09/07/3856/addother/" rel="attachment wp-att-4106"><img class="aligncenter size-medium wp-image-4106" alt="" src="/wp-content/uploads/2012/09/addOther-261x300.png" width="261" height="300" /></a></p>
<p>Now onto the code&#8230;&#8230;.import NinevehGL into your header (.h) file,</p>
<div class="wp_syntax">
<pre><span style="color: #993300;">#import</span> &lt;NinevehGL/NinevehGL.h&gt;</pre>
</div>
<p>add the delegate to your @interface, if this is missing your drawview method will never get called.</p>
<div class="wp_syntax">
<pre>@interface ViewController : UIViewController &lt;<span style="color: #333399;">NGLViewDelegate</span>&gt;;</pre>
</div>
<p>In order to see what is being rendered we will need an ivar for an NGLCamera, and for our single object, an NGLMesh. The complete code for all of this should look as follows.</p>
<div class="wp_syntax">
<pre><span style="color: #993300;">#import</span> &lt;UIKit/UIKit.h&gt;
<span style="color: #993300;">#import</span> &lt;NinevehGL/NinevehGL.h&gt; 

@interface ViewController : UIViewController &lt;<span style="color: #333399;">NGLViewDelegate</span>&gt; 
{ 
    <span style="color: #333399;">NGLCamera</span> *_camera; 
    <span style="color: #333399;">NGLMesh</span> *_mesh; 
}</pre>
</div>
<p>In your source (.m) file you must initialize your NGLView, set its delgate to self, define a dictionary with a few basic settings, and initialize the mesh and camera. I am doing this in my viewDidLoad method but depending on your needs, this could be done elsewhere.</p>
<div class="wp_syntax">
<pre>    
- (void)viewDidLoad
{
    [super viewDidLoad];
    <span style="color: #008000;">// Do any additional setup after loading the view, typically from a nib.</span>

    <span style="color: #008000;">// Setup our NGLView.</span>
    <span style="color: #333399;">NGLView</span> *theView = [[<span style="color: #333399;">NGLView</span> alloc] initWithFrame:CGRectMake(40, 40, 240, 360)];

    <span style="color: #008000;">// Set its delegate to self so the drawview method is used.</span>
    theView.delegate = self;

    <span style="color: #008000;">// Add the new view on top of our existing view.</span> 
    [self.view addSubview:theView];

    <span style="color: #008000;">// The content scale factor is used to increase the resolution to take advantage </span></pre>
<pre><span style="color: #008000;"> of retina displays and values range from 1.0 to 2.0. This sets the contentscalefactor </span></pre>
<pre><span style="color: #008000;"> to the max screen scale of the device.</span>
    theView.contentScaleFactor = [[UIScreen mainScreen] scale];

    <span style="color: #008000;">// Setup some initial environment states to be applied to our mesh.</span>
    NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
	<span style="color: #993300;">kNGLMeshCentralizeYes</span>, <span style="color: #993300;">kNGLMeshKeyCentralize</span>,
	<span style="color: #cc0000;">@"0.3"</span>, <span style="color: #993300;">kNGLMeshKeyNormalize</span>, nil];

    <span style="color: #008000;">// Initialize the mesh which includes the model file to import (.obj or .dae).</span>
    _mesh = [[<span style="color: #333399;">NGLMesh</span> alloc] initWithFile:<span style="color: #cc0000;">@"earth.obj"</span> settings:settings delegate:nil];

    <span style="color: #008000;">// Initialize the camera used to render the scene.</span>
    _camera = [[<span style="color: #333399;">NGLCamera</span> alloc] initWithMeshes:_mesh, nil];

    <span style="color: #008000;">// If a trasparent background of the NGLView is needed</span>
    <span style="color: #008000;">//theView.backgroundColor = [UIColor clearColor];</span>
    <span style="color: #008000;">//nglGlobalColorFormat(NGLColorFormatRGBA);</span>
    <span style="color: #008000;">//nglGlobalFlush();</span>

    <span style="color: #008000;">// The following command displays a 3d view status monitor that will show your current frame rate and number of polygons being rendered in the view.</span>
    [[<span style="color: #333399;">NGLDebug</span> debugMonitor] startWithView:(<span style="color: #333399;">NGLView</span> *)self.view];
}</pre>
</div>
<p>You will need to add at least one method to your source (.m) file, this is the drawView loop. This drawView loop is used to generate each frame being displayed (up to 60 per second). This drawloop is where you would affect the mesh to animate movement or create the effects your a looking to display. The  [_camera drawCamera] is needed to commit the changes and render the frame. The method usually ends with this command.</p>
<div class="wp_syntax">
<pre>-(void)drawView
{
    <span style="color: #008000;">// Rotate on Y axis</span>
    _mesh.rotateY += .5;

    <span style="color: #008000;">// Draw to our camera to display on our view</span>
    [_camera drawCamera];
}</pre>
</div>
<p>In the above example, the _mesh.rotateY += .5 is used to rotate the mesh .5 degrees each time the frame is rendered.</p>
<p>Now build and run the project and you should see a slowly spinning planet Earth. The NGLView was purposely drawn smaller than the background view in order to show how you could overlay this NGLView over any other normal view to add 3D content. If you want the background of the NGLView to be transparent, set the background color of the view to clear and add the following additional commands. There is also a status monitor that can be run to display frame rates and the number of polygons being rendered for optimization.</p>
<p><a href="/2012/09/07/3856/openglviewcapture/" rel="attachment wp-att-4180"><img class="alignleft size-medium wp-image-4180" alt="" src="/wp-content/uploads/2012/09/openGLviewCapture-162x300.png" width="162" height="300" /></a></p>
<div class="wp_syntax">
<pre><span style="color: #008000;">// If a trasparent background of the NGLView is needed</span>
 theView.backgroundColor = [UIColor clearColor];
 nglGlobalColorFormat(<span style="color: #333399;">NGLColorFormatRGBA</span>);
 nglGlobalFlush();

<span style="color: #008000;">// The following command displays a 3d view status monitor that will show your current frame rate and number of polygons being rendered in the view.</span>
 [[<span style="color: #333399;">NGLDebug</span> debugMonitor] startWithView:(<span style="color: #333399;">NGLView</span> *)self.view];</pre>
</div>
<p>There are many commands you can use to affect your object, it&#8217;s movement and how it interacts in it&#8217;s 3D environment, here are just a few basic ones. Advanced animation, movement techniques, object hit testing, custom shaders, etc. would be worthy of a separate tutorial. Enjoy.</p>
<div class="wp_syntax">
<pre><span style="color: #008000;">// rotation</span>
 _mesh.rotateX, rotateY, rotateZ

<span style="color: #008000;">// scaling</span>
 _mesh.scaleX, scaleY, scaleZ 

<span style="color: #008000;">// placement</span>
 _mesh.x,y,z 

<span style="color: #008000;">// offset center of objects rotation</span>
 _mesh.pivot = nglVec3Make(x, y, z)</pre>
</div>
<p><a title="openGLView assets" href="/wp-content/uploads/2012/09/openGLViewAssets.zip">Assets</a></p>
<p><a title="openGLview project file." href="/wp-content/uploads/2012/09/openGLview.zip">Project file</a></p>
<!-- Start Sociable --><div class="sociable"><ul class='clearfix'></ul><div onMouseout="fixOnMouseOut(this,event,'post-3856')" id="sociable-post-3856" style="display:none;">   

    <div style="top: auto; left: auto; display: block;" id="sociable">



		<div class="popup">

			<div class="content">

				<ul><li style="heigth:32px;width:32px"><a title="Facebook" class="option1_32" style="background-position:-96px 0px" rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;t=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL"></a></li><li style="heigth:32px;width:32px"><a title="Myspace" class="option1_32" style="background-position:0px -32px" rel="nofollow" target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;t=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL"></a></li><li style="heigth:32px;width:32px"><a title="Twitter" class="option1_32" style="background-position:-288px -32px" rel="nofollow" target="_blank" href="http://twitter.com/intent/tweet?text=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL%20-%20http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F%20  SHARETAG"></a></li><li style="heigth:32px;width:32px"><a title="LinkedIn" class="option1_32" style="background-position:-288px 0px" rel="nofollow" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;title=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL&amp;source=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials&amp;summary=Recently%20I%20came%20across%20an%20openGL%20ES%202.0%20engine%20that%20made%20setup%2C%20displaying%20and%20animating%20of%203D%20objects%20a%20breeze%2C%20called%20NinevehGL.%20%C2%A0This%203D%20engine%20has%20many%20great%20features%20including%20a%20full%20multithreading%20environment%2C%20to%20keep%20the%20main%20run%20loop%20free%20du"></a></li><li style="heigth:32px;width:32px"><a title="Delicious" class="option1_32" style="background-position:-32px 0px" rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;title=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL&amp;notes=Recently%20I%20came%20across%20an%20openGL%20ES%202.0%20engine%20that%20made%20setup%2C%20displaying%20and%20animating%20of%203D%20objects%20a%20breeze%2C%20called%20NinevehGL.%20%C2%A0This%203D%20engine%20has%20many%20great%20features%20including%20a%20full%20multithreading%20environment%2C%20to%20keep%20the%20main%20run%20loop%20free%20du"></a></li><li style="heigth:32px;width:32px"><a title="Digg" class="option1_32" style="background-position:-64px 0px" rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;title=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL&amp;bodytext=Recently%20I%20came%20across%20an%20openGL%20ES%202.0%20engine%20that%20made%20setup%2C%20displaying%20and%20animating%20of%203D%20objects%20a%20breeze%2C%20called%20NinevehGL.%20%C2%A0This%203D%20engine%20has%20many%20great%20features%20including%20a%20full%20multithreading%20environment%2C%20to%20keep%20the%20main%20run%20loop%20free%20du"></a></li><li style="heigth:32px;width:32px"><a title="Reddit" class="option1_32" style="background-position:-128px -32px" rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;title=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL"></a></li><li style="heigth:32px;width:32px"><a title="StumbleUpon" class="option1_32" style="background-position:-224px -32px" rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&title=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL"></a></li><li style="heigth:32px;width:32px"><a title="Google Bookmarks" class="option1_32" style="background-position:-192px 0px" rel="nofollow" target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;title=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL&amp;annotation=Recently%20I%20came%20across%20an%20openGL%20ES%202.0%20engine%20that%20made%20setup%2C%20displaying%20and%20animating%20of%203D%20objects%20a%20breeze%2C%20called%20NinevehGL.%20%C2%A0This%203D%20engine%20has%20many%20great%20features%20including%20a%20full%20multithreading%20environment%2C%20to%20keep%20the%20main%20run%20loop%20free%20du"></a></li><li style="heigth:32px;width:32px"><a title="HackerNews" class="option1_32" style="background-position:-256px 0px" rel="nofollow" target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;t=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL"></a></li><li style="heigth:32px;width:32px"><a title="MSNReporter" class="option1_32" style="background-position:-352px 0px" rel="nofollow" target="_blank" href="http://reporter.es.msn.com/?fn=contribute&amp;Title=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL&amp;URL=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;cat_id=6&amp;tag_id=31&amp;Remark=Recently%20I%20came%20across%20an%20openGL%20ES%202.0%20engine%20that%20made%20setup%2C%20displaying%20and%20animating%20of%203D%20objects%20a%20breeze%2C%20called%20NinevehGL.%20%C2%A0This%203D%20engine%20has%20many%20great%20features%20including%20a%20full%20multithreading%20environment%2C%20to%20keep%20the%20main%20run%20loop%20free%20du"></a></li><li style="heigth:32px;width:32px"><a title="BlinkList" class="option1_32" style="background-position:0px 0px" rel="nofollow" target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;Title=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL"></a></li><li style="heigth:32px;width:32px"><a title="Sphinn" class="option1_32" style="background-position:-192px -32px" rel="nofollow" target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F"></a></li><li style="heigth:32px;width:32px"><a title="Posterous" class="option1_32" style="background-position:-64px -32px" rel="nofollow" target="_blank" href="http://posterous.com/share?linkto=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;title=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL&amp;selection=Recently%20I%20came%20across%20an%20openGL%20ES%202.0%20engine%20that%20made%20setup%2C%20displaying%20and%20animating%20of%203D%20objects%20a%20breeze%2C%20called%20NinevehGL.%20%C2%A0This%203D%20engine%20has%20many%20great%20features%20including%20a%20full%20multithreading%20environment%2C%20to%20keep%20the%20main%20run%20loop%20free%20du"></a></li><li style="heigth:32px;width:32px"><a title="Tumblr" class="option1_32" style="background-position:-256px -32px" rel="nofollow" target="_blank" href="http://www.tumblr.com/share?v=3&amp;u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;t=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL&amp;s=Recently%20I%20came%20across%20an%20openGL%20ES%202.0%20engine%20that%20made%20setup%2C%20displaying%20and%20animating%20of%203D%20objects%20a%20breeze%2C%20called%20NinevehGL.%20%C2%A0This%203D%20engine%20has%20many%20great%20features%20including%20a%20full%20multithreading%20environment%2C%20to%20keep%20the%20main%20run%20loop%20free%20du"></a></li><li style="heigth:32px;width:32px"><a title="email" class="option1_32" style="background-position:-160px 0px" rel="nofollow" target="_blank" href="https://mail.google.com/mail/?view=cm&fs=1&to&su=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL&body=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&ui=2&tf=1&shva=1"></a></li><li style="heigth:32px;width:32px"><a title="Google Reader" class="option1_32" style="background-position:-224px 0px" rel="nofollow" target="_blank" href="http://www.google.com/reader/link?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;title=Adding%20an%20OpenGL%20ES%20view%20to%20your%20project%20using%20NinevehGL&amp;srcURL=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F09%2F07%2F3856%2F&amp;srcTitle=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials"></a></li><li style="heigth:32px;width:32px"><a class="option1_32" style="cursor:pointer;background-position:-128px 0px" rel="nofollow" title="Add to favorites - doesn't work in Chrome"  onClick="javascript:AddToFavorites();"></a></li><li style="heigth:32px;width:32px"><a style="cursor:poainter" rel="nofollow"   onMouseOver="more(this,'post-3856')"><img style='margin-top:9px' src='/wp-content/plugins/sociable/images/more.png'></a></li></ul>			

			</div>        

		  <a style="cursor:pointer" onclick="hide_sociable('post-3856',true)" class="close">

		  <img onclick="hide_sociable('post-3856',true)" title="close" src="/wp-content/plugins/sociable/images/closelabel.png">

		  </a>

		</div>

	</div> 

  </div></div><div class='sociable' style='float:none'><ul class='clearfix'><li id="Twitter_Counter"><a href="https://twitter.com/share" data-text="Adding an OpenGL ES view to your project using NinevehGL - http://icodeblog.com/2012/09/07/3856/" data-url="http://icodeblog.com/2012/09/07/3856/" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></li><li id="Facebook_Counter"><iframe src="http://www.facebook.com/plugins/like.php?href=http://icodeblog.com/2012/09/07/3856/&send=false&layout=button_count&show_faces=false&action=like&colorscheme=light&font" scrolling="no" frameborder="0" style="border:none; overflow:hidden;height:32px;width:100px" allowTransparency="true"></iframe></li><li id="Google_p"><g:plusone annotation="bubble" href="/2012/09/07/3856/" size="medium"></g:plusone></li><li id="LinkedIn_Counter"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="http://icodeblog.com/2012/09/07/3856/" data-counter="right"></script></li></ul></div><!-- End Sociable -->]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2012/09/07/3856/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Unzipping Files In iOS Using ZipArchive</title>
		<link>http://icodeblog.com/2012/08/13/unzipping-files-using-zip-archive/</link>
		<comments>http://icodeblog.com/2012/08/13/unzipping-files-using-zip-archive/#comments</comments>
		<pubDate>Mon, 13 Aug 2012 09:00:04 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Third-Party]]></category>
		<category><![CDATA[ZipArchive]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=3788</guid>
		<description><![CDATA[In this tutorial, I am going to demonstrate how you can zip and unzip files from within your iOS applications.  We will be using a third party library called ZipArchive to achieve this.  While there are a couple solutions out there to zip and unzip files, I feel that the ZipArchive library was the fastest and easiest way to get up and running.
Why Would I want To Unzip Files?
That&#8217;s a great question.  There are a number of  ...]]></description>
				<content:encoded><![CDATA[<p>In this tutorial, I am going to demonstrate how you can zip and unzip files from within your iOS applications.  We will be using a third party library called ZipArchive to achieve this.  While there are a couple solutions out there to zip and unzip files, I feel that the ZipArchive library was the fastest and easiest way to get up and running.</p>
<h2>Why Would I want To Unzip Files?</h2>
<p>That&#8217;s a great question.  There are a number of reasons why you might want to support zipping and unzipping files inside of your applications. Here are just a few:</p>
<p><strong>Apple&#8217;s 50 MB App Store Download Cap</strong></p>
<p>Apple has imposed a 50MB download limit over 3G on applications downloaded to appease carriers and not hog all of their bandwidth.  One way to circumvent this is to keep your binaries very small, and download the resources your application needs.  The best way to package these resources is of course, a zip file.  So the process (as you will see demoed below), is to open your app, check for resource updates, download the zip file, and unzip it.  Now you can ship smaller applications, that fetch their resources dynamically.</p>
<p><strong>Dynamic Updates To Content</strong></p>
<p>I touched on this above.  When your application needs updated assets, the common practice is to submit an update to the App Store.  This could take up to a week for Apple to Review and publish.  A faster approach is to zip your assets up and stick them on a server somewhere (even your Dropbox) and have your app download and unzip them.  This way, whenever you want to make asset-based changes to your application, you won&#8217;t need to submit another copy of it to the store.</p>
<p><strong>Downloading Zip Files From The Web</strong></p>
<p>One huge downfall of Safari and the Mail app is, they are unable to open zipped files.  It would be nice to offer some sort of support to view zipped archives on your device.  Many of the &#8220;download&#8221; apps in the store support this, and you can too with some help from ZipArchive.</p>
<h2>Setting Up Your Project</h2>
<p>Head over to <a href="http://code.google.com/p/ziparchive/">http://code.google.com/p/ziparchive/</a> and checkout a copy of ZipArchive.    Or you can just type this into your terminal.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">svn checkout http<span style="color: #002200;">:</span><span style="color: #11740a; font-style: italic;">//ziparchive.googlecode.com/svn/trunk/ziparchive-read-only</span></pre></td></tr></table></div>

<p>Once you have cloned the repository, delete the MakeFile file from the minizip folder.  We will let XCode build our files.  Now, drag this minizip folder as well as the ZipArchive.h and ZipArchive.mm files into your project, making sure to check &#8220;Create <strong>groups</strong> for any added folders&#8221;.  Also, be sure your target is checked.</p>
<p><a href="/wp-content/uploads/2012/08/Screen-Shot-2012-08-06-at-10.44.07-AM.png"><img src="/wp-content/uploads/2012/08/Screen-Shot-2012-08-06-at-10.44.07-AM-300x202.png" alt="" title="Screen Shot 2012-08-06 at 10.44.07 AM" width="300" height="202" class="alignnone size-medium wp-image-3791" /></a></p>
<p><strong>Note: No ARC Support</strong></p>
<p>If you are using an ARC enabled project, you will need to tell the compiler not to use ARC for ZipArchive.  To do this, click on the project in the left hand column.  Then click on your target in the middle column and select the &#8220;Build Phases&#8221; tab.</p>
<p>Expand the &#8220;Compile Sources&#8221; area, locate <strong>ZipArchive.mm</strong> and double click on it.  In the box that pops up, type in <strong>-fno-objc-arc</strong> and click Done.</p>
<p><a href="/wp-content/uploads/2012/08/Screen-Shot-2012-08-06-at-10.47.00-AM.png"><img src="/wp-content/uploads/2012/08/Screen-Shot-2012-08-06-at-10.47.00-AM.png" alt="" title="Screen Shot 2012-08-06 at 10.47.00 AM" width="266" height="191" class="alignnone size-full wp-image-3792" /></a></p>
<p><strong>Linking libz</strong></p>
<p>The last step is to link your project against <strong>libz.1.2.5.dylib</strong>.  From the <strong>Build Phases</strong> screen you navigated to above, expand the <strong>Link Binary With Libraries</strong> section and click the &#8220;+&#8221; button to add a new library.  Search the list for libz.1.2.5.dylib, select it and click Add.</p>
<p><a href="/wp-content/uploads/2012/08/Screen-Shot-2012-08-06-at-10.50.19-AM.png"><img src="/wp-content/uploads/2012/08/Screen-Shot-2012-08-06-at-10.50.19-AM-260x300.png" alt="" title="Screen Shot 2012-08-06 at 10.50.19 AM" width="260" height="300" class="alignnone size-medium wp-image-3794" /></a></p>
<p>Now, compile your project and it should succeed with no errors.  One thing to note is ZipArchive might produce some warnings, they are not a big deal, but if you are a warning Nazi (you should be), dig into the code and see if you can solve them yourself.</p>
<h2>Downloading And Unzipping Files</h2>
<p>I will now show you how easy it is to download a zip file from the web, unzip its contents, and use them in your project.  The method of which we will download the files is very basic and most likely wouldn&#8217;t be used in production without further error reporting and checking.</p>
<p>The sample project has a view that looks like this:</p>
<p><a href="/wp-content/uploads/2012/08/Screen-Shot-2012-08-09-at-11.45.31-AM.png"><img src="/wp-content/uploads/2012/08/Screen-Shot-2012-08-09-at-11.45.31-AM-159x300.png" alt="" title="Screen Shot 2012-08-09 at 11.45.31 AM" width="159" height="300" class="aligncenter size-medium wp-image-3818" /></a></p>
<p>It&#8217;s basically a UIImageView and a UILabel.  Inside of the view controller I have set up IBOutlets for these two items.  Make sure and <a href="/wp-content/uploads/2012/08/ZipTest.zip">download the sample project</a> to see the implementation details.  We will be downloading a zip file from the web that contains an image and a text file which you can see displayed in the screenshot above.  Once unzipped, the image will be set as the viewable image in our UIImageView and the textual contents of the .txt file will be displayed inside of the UILabel.</p>
<p>**1. Import the ZipArchive headers **</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;ZipArchive.h&quot;</span></pre></td></tr></table></div>

<p><strong>2. Download the the zip file</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">    <span style="color: #11740a; font-style: italic;">// 1 </span>
    dispatch_queue_t queue <span style="color: #002200;">=</span> dispatch_get_global_queue<span style="color: #002200;">&#40;</span>
                                                       DISPATCH_QUEUE_PRIORITY_DEFAULT, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
    dispatch_async<span style="color: #002200;">&#40;</span>queue, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
        <span style="color: #400080;">NSURL</span> <span style="color: #002200;">*</span>url <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> URLWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://icodeblog.com/wp-content/uploads/2012/08/zipfile.zip&quot;</span><span style="color: #002200;">&#93;</span>;
        <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
        <span style="color: #11740a; font-style: italic;">// 2</span>
        <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSData</span> dataWithContentsOfURL<span style="color: #002200;">:</span>url options<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> error<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>error<span style="color: #002200;">&#41;</span>
        <span style="color: #002200;">&#123;</span>        
            <span style="color: #11740a; font-style: italic;">// 3</span>
            <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>paths <span style="color: #002200;">=</span> NSSearchPathForDirectoriesInDomains<span style="color: #002200;">&#40;</span>NSCachesDirectory, NSUserDomainMask, <span style="color: #a61390;">YES</span><span style="color: #002200;">&#41;</span>;
            <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>path <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>paths objectAtIndex<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
            <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>zipPath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>path stringByAppendingPathComponent<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;zipfile.zip&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
            <span style="color: #002200;">&#91;</span>data writeToFile<span style="color: #002200;">:</span>zipPath options<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> error<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span>;
&nbsp;
            <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>error<span style="color: #002200;">&#41;</span>
            <span style="color: #002200;">&#123;</span>
                <span style="color: #11740a; font-style: italic;">// TODO: Unzip</span>
            <span style="color: #002200;">&#125;</span>
            <span style="color: #a61390;">else</span>
            <span style="color: #002200;">&#123;</span>
                NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Error saving file %@&quot;</span>,error<span style="color: #002200;">&#41;</span>;
            <span style="color: #002200;">&#125;</span>
        <span style="color: #002200;">&#125;</span>
        <span style="color: #a61390;">else</span>
        <span style="color: #002200;">&#123;</span>
            NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Error downloading zip file: %@&quot;</span>, error<span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>This preliminary code downloads a zip file from iCodeBlog and saves it to the caches directory for the application.</p>
<ol>
<li>Creates a dispatch queue in which to run our code on with default priority.</li>
<li>Quick and dirty way of fetching data from the web.  </li>
<li>Resolves the path to the caches directory and writes out the downloaded data to a local zip file</li>
</ol>
<p>Now that you have it downloading the file to disk, it&#8217;s time to unzip that file and make use of it&#8217;s contents.</p>
<p><strong>3. Unzipping the downloaded file</strong></p>
<p>The last step here is to unzip the file you just downloaded.  To be clear, it was save to the path <strong>/Library/Caches/zipfile.zip</strong> and once extracted, it&#8217;s contents will be inside of the Caches folder as well.</p>
<p>Replace the <strong>//TODO: Unzip</strong> in the code above, with the following code:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">ZipArchive <span style="color: #002200;">*</span>za <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>ZipArchive alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
<span style="color: #11740a; font-style: italic;">// 1</span>
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>za UnzipOpenFile<span style="color: #002200;">:</span> zipPath<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>      
    <span style="color: #11740a; font-style: italic;">// 2      </span>
    <span style="color: #a61390;">BOOL</span> ret <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>za UnzipFileTo<span style="color: #002200;">:</span> path overWrite<span style="color: #002200;">:</span> <span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">NO</span> <span style="color: #002200;">==</span> ret<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#123;</span><span style="color: #002200;">&#125;</span> <span style="color: #002200;">&#91;</span>za UnzipCloseFile<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// 3</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>imageFilePath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>path stringByAppendingPathComponent<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;photo.png&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>textFilePath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>path stringByAppendingPathComponent<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;text.txt&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>imageData <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSData</span> dataWithContentsOfFile<span style="color: #002200;">:</span>imageFilePath options<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> error<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
    UIImage <span style="color: #002200;">*</span>img <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIImage imageWithData<span style="color: #002200;">:</span>imageData<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>textString <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithContentsOfFile<span style="color: #002200;">:</span>textFilePath 
        encoding<span style="color: #002200;">:</span>NSASCIIStringEncoding error<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// 4           </span>
    dispatch_async<span style="color: #002200;">&#40;</span>dispatch_get_main_queue<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
        self.imageView.image <span style="color: #002200;">=</span> img;
        self.label.text <span style="color: #002200;">=</span> textString;
    <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>Here is an explanation of what&#8217;s going on.</p>
<ol>
<li>Opens the file and unzips it in memory</li>
<li>Writes the unzipped contents out to a given path (<strong>Caches</strong> folder)</li>
<li>Makes use of the unzipped files</li>
<li>Updates the UI (on the main thread of course) with the newly fetched data.</li>
</ol>
<p>It really is that simple.</p>
<h2>Zipping Files</h2>
<p>Now you are going to see how to go the other way and zip up some files on disk.  Again, this could be particularly handy when you want to allow your users to share groups of files via the web or email.</p>
<p>If you completed the steps above, your caches folder should have some files lying around that we can just zip up again and send off.  We are going to zip up the two files you previously unzipped, stuff them into a new zip file, and write that out to the documents directory.</p>
<p>In my sample project, I have created a new button at the top that says &#8220;Zip Files&#8221; which links to an IBAction called zipFilesButtonPressed: when tapped. That is where I will be doing the zipping:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>zipFilesButtonPressed<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender
<span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">// 1</span>
    <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>paths <span style="color: #002200;">=</span> NSSearchPathForDirectoriesInDomains<span style="color: #002200;">&#40;</span>NSDocumentDirectory, NSUserDomainMask, <span style="color: #a61390;">YES</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>docspath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>paths objectAtIndex<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// 2</span>
    paths <span style="color: #002200;">=</span> NSSearchPathForDirectoriesInDomains<span style="color: #002200;">&#40;</span>NSCachesDirectory, NSUserDomainMask, <span style="color: #a61390;">YES</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>cachePath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>paths objectAtIndex<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// 3</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>zipFile <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>docspath stringByAppendingPathComponent<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;newzipfile.zip&quot;</span><span style="color: #002200;">&#93;</span>;       
&nbsp;
    <span style="color: #11740a; font-style: italic;">// 4</span>
    ZipArchive <span style="color: #002200;">*</span>za <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>ZipArchive alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>za CreateZipFile2<span style="color: #002200;">:</span>zipFile<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// 5</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>imagePath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>cachePath stringByAppendingPathComponent<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;photo.png&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>textPath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>cachePath stringByAppendingPathComponent<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;text.txt&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// 6</span>
    <span style="color: #002200;">&#91;</span>za addFileToZip<span style="color: #002200;">:</span>imagePath newname<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;NewPhotoName.png&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>za addFileToZip<span style="color: #002200;">:</span>textPath newname<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;NewTextName.txt&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// 7</span>
    <span style="color: #a61390;">BOOL</span> success <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>za CloseZipFile2<span style="color: #002200;">&#93;</span>;    
    NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Zipped file with result %d&quot;</span>,success<span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Here is what&#8217;s going on:</p>
<ol>
<li>Resolve the path to the documents directory.  We will need this when determining the path to write out our new zip file.</li>
<li>Resolve the path to the caches directory.  This is used to fetch the files that will be zipped up.</li>
<li>Determines the path the zip file we will be writing out.</li>
<li>Instantiates the ZipArchive object and tells it to create a new &#8220;in-memory&#8221; zip file.  Note, the file won&#8217;t be written out until you call the corresponding CloseZipFile2 method.</li>
<li>Resolve the path to the files that will be zipped up.</li>
<li>Add the files to the zip archive.  You can add as many files as you would like here.  You can even add directories (ie you could have added the entire caches directory if you wanted to).</li>
<li>Write out the zip file and close it.  Just to test, we log the result to ensure that the zipping was successful. </li>
</ol>
<p>After running through the application, tapping on the &#8220;Zip Files&#8221; button, look inside of the Application&#8217;s Documents folder (located ~/Library/Application Support/iPhone Simulator/[iOS Version]/Applications/[Unique ID]/Documents].   It should contain a single zip file called newzipfile.zip.  If you unzip it, you <em>should</em> see the two files that you stuffed in there extracted.</p>
<h2>Conclusion</h2>
<p>You have now seen how to zip and unzip files on iOS devices using the ZipArchive library.  You can download the sample project at the bottom of this post.  As always, if you have any questions or comments, feel free to write them in the comments of this post or write them to me on Twitter <a href="http://twitter.com/brandontreb">@brandontreb</a>.</p>
<p>Happy iCoding!</p>
<p><a href='/wp-content/uploads/2012/08/ZipTest.zip'>Download The Sample Project</a></p>
<!-- Start Sociable --><div class="sociable"><ul class='clearfix'></ul><div onMouseout="fixOnMouseOut(this,event,'post-3788')" id="sociable-post-3788" style="display:none;">   

    <div style="top: auto; left: auto; display: block;" id="sociable">



		<div class="popup">

			<div class="content">

				<ul><li style="heigth:32px;width:32px"><a title="Facebook" class="option1_32" style="background-position:-96px 0px" rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;t=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive"></a></li><li style="heigth:32px;width:32px"><a title="Myspace" class="option1_32" style="background-position:0px -32px" rel="nofollow" target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;t=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive"></a></li><li style="heigth:32px;width:32px"><a title="Twitter" class="option1_32" style="background-position:-288px -32px" rel="nofollow" target="_blank" href="http://twitter.com/intent/tweet?text=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive%20-%20http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F%20  SHARETAG"></a></li><li style="heigth:32px;width:32px"><a title="LinkedIn" class="option1_32" style="background-position:-288px 0px" rel="nofollow" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;title=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive&amp;source=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials&amp;summary=In%20this%20tutorial%2C%20I%20am%20going%20to%20demonstrate%20how%20you%20can%20zip%20and%20unzip%20files%20from%20within%20your%20iOS%20applications.%20%20We%20will%20be%20using%20a%20third%20party%20library%20called%20ZipArchive%20to%20achieve%20this.%20%20While%20there%20are%20a%20couple%20solutions%20out%20there%20to%20zip%20and%20unzip%20f"></a></li><li style="heigth:32px;width:32px"><a title="Delicious" class="option1_32" style="background-position:-32px 0px" rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;title=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive&amp;notes=In%20this%20tutorial%2C%20I%20am%20going%20to%20demonstrate%20how%20you%20can%20zip%20and%20unzip%20files%20from%20within%20your%20iOS%20applications.%20%20We%20will%20be%20using%20a%20third%20party%20library%20called%20ZipArchive%20to%20achieve%20this.%20%20While%20there%20are%20a%20couple%20solutions%20out%20there%20to%20zip%20and%20unzip%20f"></a></li><li style="heigth:32px;width:32px"><a title="Digg" class="option1_32" style="background-position:-64px 0px" rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;title=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive&amp;bodytext=In%20this%20tutorial%2C%20I%20am%20going%20to%20demonstrate%20how%20you%20can%20zip%20and%20unzip%20files%20from%20within%20your%20iOS%20applications.%20%20We%20will%20be%20using%20a%20third%20party%20library%20called%20ZipArchive%20to%20achieve%20this.%20%20While%20there%20are%20a%20couple%20solutions%20out%20there%20to%20zip%20and%20unzip%20f"></a></li><li style="heigth:32px;width:32px"><a title="Reddit" class="option1_32" style="background-position:-128px -32px" rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;title=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive"></a></li><li style="heigth:32px;width:32px"><a title="StumbleUpon" class="option1_32" style="background-position:-224px -32px" rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&title=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive"></a></li><li style="heigth:32px;width:32px"><a title="Google Bookmarks" class="option1_32" style="background-position:-192px 0px" rel="nofollow" target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;title=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive&amp;annotation=In%20this%20tutorial%2C%20I%20am%20going%20to%20demonstrate%20how%20you%20can%20zip%20and%20unzip%20files%20from%20within%20your%20iOS%20applications.%20%20We%20will%20be%20using%20a%20third%20party%20library%20called%20ZipArchive%20to%20achieve%20this.%20%20While%20there%20are%20a%20couple%20solutions%20out%20there%20to%20zip%20and%20unzip%20f"></a></li><li style="heigth:32px;width:32px"><a title="HackerNews" class="option1_32" style="background-position:-256px 0px" rel="nofollow" target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;t=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive"></a></li><li style="heigth:32px;width:32px"><a title="MSNReporter" class="option1_32" style="background-position:-352px 0px" rel="nofollow" target="_blank" href="http://reporter.es.msn.com/?fn=contribute&amp;Title=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive&amp;URL=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;cat_id=6&amp;tag_id=31&amp;Remark=In%20this%20tutorial%2C%20I%20am%20going%20to%20demonstrate%20how%20you%20can%20zip%20and%20unzip%20files%20from%20within%20your%20iOS%20applications.%20%20We%20will%20be%20using%20a%20third%20party%20library%20called%20ZipArchive%20to%20achieve%20this.%20%20While%20there%20are%20a%20couple%20solutions%20out%20there%20to%20zip%20and%20unzip%20f"></a></li><li style="heigth:32px;width:32px"><a title="BlinkList" class="option1_32" style="background-position:0px 0px" rel="nofollow" target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;Title=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive"></a></li><li style="heigth:32px;width:32px"><a title="Sphinn" class="option1_32" style="background-position:-192px -32px" rel="nofollow" target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F"></a></li><li style="heigth:32px;width:32px"><a title="Posterous" class="option1_32" style="background-position:-64px -32px" rel="nofollow" target="_blank" href="http://posterous.com/share?linkto=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;title=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive&amp;selection=In%20this%20tutorial%2C%20I%20am%20going%20to%20demonstrate%20how%20you%20can%20zip%20and%20unzip%20files%20from%20within%20your%20iOS%20applications.%20%20We%20will%20be%20using%20a%20third%20party%20library%20called%20ZipArchive%20to%20achieve%20this.%20%20While%20there%20are%20a%20couple%20solutions%20out%20there%20to%20zip%20and%20unzip%20f"></a></li><li style="heigth:32px;width:32px"><a title="Tumblr" class="option1_32" style="background-position:-256px -32px" rel="nofollow" target="_blank" href="http://www.tumblr.com/share?v=3&amp;u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;t=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive&amp;s=In%20this%20tutorial%2C%20I%20am%20going%20to%20demonstrate%20how%20you%20can%20zip%20and%20unzip%20files%20from%20within%20your%20iOS%20applications.%20%20We%20will%20be%20using%20a%20third%20party%20library%20called%20ZipArchive%20to%20achieve%20this.%20%20While%20there%20are%20a%20couple%20solutions%20out%20there%20to%20zip%20and%20unzip%20f"></a></li><li style="heigth:32px;width:32px"><a title="email" class="option1_32" style="background-position:-160px 0px" rel="nofollow" target="_blank" href="https://mail.google.com/mail/?view=cm&fs=1&to&su=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive&body=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&ui=2&tf=1&shva=1"></a></li><li style="heigth:32px;width:32px"><a title="Google Reader" class="option1_32" style="background-position:-224px 0px" rel="nofollow" target="_blank" href="http://www.google.com/reader/link?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;title=Unzipping%20Files%20In%20iOS%20Using%20ZipArchive&amp;srcURL=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F13%2Funzipping-files-using-zip-archive%2F&amp;srcTitle=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials"></a></li><li style="heigth:32px;width:32px"><a class="option1_32" style="cursor:pointer;background-position:-128px 0px" rel="nofollow" title="Add to favorites - doesn't work in Chrome"  onClick="javascript:AddToFavorites();"></a></li><li style="heigth:32px;width:32px"><a style="cursor:poainter" rel="nofollow"   onMouseOver="more(this,'post-3788')"><img style='margin-top:9px' src='/wp-content/plugins/sociable/images/more.png'></a></li></ul>			

			</div>        

		  <a style="cursor:pointer" onclick="hide_sociable('post-3788',true)" class="close">

		  <img onclick="hide_sociable('post-3788',true)" title="close" src="/wp-content/plugins/sociable/images/closelabel.png">

		  </a>

		</div>

	</div> 

  </div></div><div class='sociable' style='float:none'><ul class='clearfix'><li id="Twitter_Counter"><a href="https://twitter.com/share" data-text="Unzipping Files In iOS Using ZipArchive - http://icodeblog.com/2012/08/13/unzipping-files-using-zip-archive/" data-url="http://icodeblog.com/2012/08/13/unzipping-files-using-zip-archive/" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></li><li id="Facebook_Counter"><iframe src="http://www.facebook.com/plugins/like.php?href=http://icodeblog.com/2012/08/13/unzipping-files-using-zip-archive/&send=false&layout=button_count&show_faces=false&action=like&colorscheme=light&font" scrolling="no" frameborder="0" style="border:none; overflow:hidden;height:32px;width:100px" allowTransparency="true"></iframe></li><li id="Google_p"><g:plusone annotation="bubble" href="/2012/08/13/unzipping-files-using-zip-archive/" size="medium"></g:plusone></li><li id="LinkedIn_Counter"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="http://icodeblog.com/2012/08/13/unzipping-files-using-zip-archive/" data-counter="right"></script></li></ul></div><!-- End Sociable -->]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2012/08/13/unzipping-files-using-zip-archive/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Using Method-Swizzling to help with Test Driven Development</title>
		<link>http://icodeblog.com/2012/08/08/using-method-swizzling-to-help-with-test-driven-development/</link>
		<comments>http://icodeblog.com/2012/08/08/using-method-swizzling-to-help-with-test-driven-development/#comments</comments>
		<pubDate>Wed, 08 Aug 2012 08:00:22 +0000</pubDate>
		<dc:creator><![CDATA[dpettigrew]]></dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Advanced]]></category>
		<category><![CDATA[hamcrest]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[mocking]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[ocunit]]></category>
		<category><![CDATA[runtime]]></category>
		<category><![CDATA[swizzling]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[test driven development]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=3741</guid>
		<description><![CDATA[Introduction
In this blog post I will demonstrate how to mock HTTP requests using an Objective-C runtime dynamic method replacement technique known as method swizzling. I will show how this can be used in tandem with some unit test technologies to help with development of iOS web-service client side code.
In this example, the actual work of the HTTP request is embodied in my AsyncURLConnection class. It uses NSURLConnection to perform an NSURLRequest in an asynchronous manner, using completion handler blocks to return  ...]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>In this blog post I will demonstrate how to mock HTTP requests using an Objective-C runtime dynamic method replacement technique known as <em>method swizzling</em>. I will show how this can be used in tandem with some unit test technologies to help with development of iOS web-service client side code.</p>
<p>In this example, the actual work of the HTTP request is embodied in my AsyncURLConnection class. It uses NSURLConnection to perform an NSURLRequest in an asynchronous manner, using completion handler blocks to return the response to the caller. I could have chosen to mock the native APIs but mocking at the AsyncURLConnection level provides the desired effect more easily.</p>
<h2>Method Swizzling Helper Class</h2>
<p>This is a generic helper class for method swizzling (swapping). This gets used in tests as seen below. The</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">swizzleClassMethod<span style="color: #002200;">:</span>selector<span style="color: #002200;">:</span>swizzleClass<span style="color: #002200;">:</span></pre></td></tr></table></div>

<p>method takes a class and a method selector along with a class with an alternative implementation of the method given by the selector. The class swaps the implementation of the existing class method with the corresponding method in the swizzleClass.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &amp;lt;Foundation/Foundation.h&amp;gt;</span>
<span style="color: #6e371a;">#import &amp;lt;objc/runtime.h&amp;gt;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> Swizzler <span style="color: #002200;">:</span> <span style="color: #400080;">NSObject</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>swizzleClassMethod<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">Class</span><span style="color: #002200;">&#41;</span>target_class selector<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">SEL</span><span style="color: #002200;">&#41;</span>selector swizzleClass<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">Class</span><span style="color: #002200;">&#41;</span>swizzleClass;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>deswizzle;
&nbsp;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #6e371a;">#import &quot;Swizzler.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> Swizzler
&nbsp;
Method originalMethod <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
Method swizzleMethod <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">/**
Swaps the implementation of an existing class method with the corresponding method in the swizzleClass.
 */</span>
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>swizzleClassMethod<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">Class</span><span style="color: #002200;">&#41;</span>targetClass selector<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">SEL</span><span style="color: #002200;">&#41;</span>selector swizzleClass<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">Class</span><span style="color: #002200;">&#41;</span>swizzleClass
<span style="color: #002200;">&#123;</span>
	originalMethod <span style="color: #002200;">=</span> class_getClassMethod<span style="color: #002200;">&#40;</span>targetClass, selector<span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// save the oringinal implementation so it can be restored</span>
	swizzleMethod <span style="color: #002200;">=</span> class_getClassMethod<span style="color: #002200;">&#40;</span>swizzleClass, selector<span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// save the replacement method</span>
	method_exchangeImplementations<span style="color: #002200;">&#40;</span>originalMethod, swizzleMethod<span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// perform the swap, replacing the original with the swizzle method implementation.</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">/**
 Restores the implementation of an existing class method with its original implementation.
 */</span>
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>deswizzle
<span style="color: #002200;">&#123;</span>
	method_exchangeImplementations<span style="color: #002200;">&#40;</span>swizzleMethod, originalMethod<span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// perform the swap, replacing the previously swizzled method with the original implementation.</span>
	swizzleMethod <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
	originalMethod <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<h2>Class to be mocked</h2>
<p>This is the interface of a class that connects and loads a URL. I will be replacing the implementation so its details are left out of here for brevity.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &amp;lt;Foundation/Foundation.h&amp;gt;</span>
&nbsp;
<span style="color: #a61390;">typedef</span> <span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>completeBlock_t<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data<span style="color: #002200;">&#41;</span>;
<span style="color: #a61390;">typedef</span> <span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>errorBlock_t<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error<span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #a61390;">@interface</span> AsyncURLConnection <span style="color: #002200;">:</span> <span style="color: #400080;">NSObject</span>
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSMutableData</span> <span style="color: #002200;">*</span>data;
    completeBlock_t completeBlock;
    errorBlock_t errorBlock;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">/**
 Asynchronously performs an HTTP GET - invokes one of the blocks depending on the response to the request 
*/</span>
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>request<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>requestUrl completeBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>completeBlock_t<span style="color: #002200;">&#41;</span>aCompleteBlock errorBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>errorBlock_t<span style="color: #002200;">&#41;</span>anErrorBlock;
&nbsp;
<span style="color: #11740a; font-style: italic;">/**
 Initializes and asynchronously performs an HTTP GET - invokes one of the blocks depending on the response to the request
 */</span>
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>initWithRequest<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>requestUrl completeBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>completeBlock_t<span style="color: #002200;">&#41;</span>aCompleteBlock errorBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>errorBlock_t<span style="color: #002200;">&#41;</span>anErrorBlock;
&nbsp;
<span style="color: #11740a; font-style: italic;">// If both HTTP Basic authentication optional parameters are non-empty strings, request will encode the URL with them.</span>
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, copy<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>authUserName; <span style="color: #11740a; font-style: italic;">// HTTP Basic authentication optional parameter</span>
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, copy<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>authPassword; <span style="color: #11740a; font-style: italic;">// HTTP Basic authentication optional parameter</span>
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, copy<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>accept; <span style="color: #11740a; font-style: italic;">// Optional parameter to set the response type accepted (default is @&quot;application/json&quot;)</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<h2>Example of Usage in a Test</h2>
<p>In this test I am testing that I am correctly processing the JSON data returned from the web service. However, I want to isolate the actual web service from the test. I want a test to validate the creation of the NSDictionary response object from the JSON.<br />
As an aside, by removing the Swizzler code, this test could be run against the actual web service; but that is not the intent here.<br />
Here is what the JSON response looks like &#8211;</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span>
    <span style="color: #3366CC;">&quot;coaches&quot;</span> <span style="color: #339933;">:</span>
	<span style="color: #009900;">&#91;</span>
     <span style="color: #009900;">&#123;</span>
     <span style="color: #3366CC;">&quot;id&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;name&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Jeff Tucker&quot;</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;thumbnail_url&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;http://img.breakingmuscle.com/sites/default/files/imagecache/full_portrait/images/author/64337_10150578149548471_1189630488_n.jpg&quot;</span>
     <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
     <span style="color: #009900;">&#123;</span>
     <span style="color: #3366CC;">&quot;id&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;name&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Traver H. Boehm&quot;</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;thumbnail_url&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;http://img.breakingmuscle.com/sites/default/files/imagecache/full_portrait/images/author/traver.jpg&quot;</span>
     <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
     <span style="color: #009900;">&#123;</span>
     <span style="color: #3366CC;">&quot;id&quot;</span> <span style="color: #339933;">:</span><span style="color: #CC0000;">3</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;name&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Jeff Tucker&quot;</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;thumbnail_url&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;http://img.breakingmuscle.com/sites/default/files/imagecache/full_portrait/images/author/64337_10150578149548471_1189630488_n.jpg&quot;</span>
     <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
     <span style="color: #009900;">&#123;</span>
     <span style="color: #3366CC;">&quot;id&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;name&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Traver H. Boehm&quot;</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;thumbnail_url&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;http://img.breakingmuscle.com/sites/default/files/imagecache/full_portrait/images/author/traver.jpg&quot;</span>
     <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
     <span style="color: #009900;">&#123;</span>
     <span style="color: #3366CC;">&quot;id&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;name&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Jeff Tucker&quot;</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;thumbnail_url&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;http://img.breakingmuscle.com/sites/default/files/imagecache/full_portrait/images/author/64337_10150578149548471_1189630488_n.jpg&quot;</span>
     <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
     <span style="color: #009900;">&#123;</span>
     <span style="color: #3366CC;">&quot;id&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">6</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;name&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Traver H. Boehm&quot;</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;thumbnail_url&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;http://img.breakingmuscle.com/sites/default/files/imagecache/full_portrait/images/author/traver.jpg&quot;</span>
     <span style="color: #009900;">&#125;</span>
     <span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>
    <span style="color: #3366CC;">&quot;per_page&quot;</span><span style="color: #339933;">:</span> <span style="color: #CC0000;">6</span><span style="color: #339933;">,</span>
    <span style="color: #3366CC;">&quot;page&quot;</span><span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span>
    <span style="color: #3366CC;">&quot;total&quot;</span> <span style="color: #339933;">:</span> <span style="color: #CC0000;">11</span><span style="color: #339933;">,</span>
    <span style="color: #3366CC;">&quot;total_pages&quot;</span><span style="color: #339933;">:</span> <span style="color: #CC0000;">2</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The method under test here is:-</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>loadCollectionFromEndpoint<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>endpoint successBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>JSONLoaderLoadSuccessBlock<span style="color: #002200;">&#41;</span>successBlock failBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>JSONLoaderLoadFailBlock<span style="color: #002200;">&#41;</span>failBlock</pre></td></tr></table></div>

<p>This method calls the AsyncURLConnection class method</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>request<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>requestUrl completeBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>completeBlock_t<span style="color: #002200;">&#41;</span>completeBlock errorBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>errorBlock_t<span style="color: #002200;">&#41;</span>errorBlock;</pre></td></tr></table></div>

<p>I will replace the existing implementation of that method with one that does not actually make an HTTP request, but instead gets JSON from a local file.</p>
<p>The unit test uses <a href="https://github.com/hamcrest/OCHamcrest">OCHamcrest</a> matchers and XCode&#8217;s built in <a href="http://www.sente.ch/software/ocunit/">OCUnit</a>.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>test_loadPopularCoaches_success
<span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">// Test set-up</span>
    Swizzler <span style="color: #002200;">*</span>swizzler <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>Swizzler new<span style="color: #002200;">&#93;</span>;
    <span style="color: #11740a; font-style: italic;">// Replace the actual AsyncURLConnection method with our own test one.</span>
    <span style="color: #002200;">&#91;</span>swizzler swizzleClassMethod<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>AsyncURLConnection class<span style="color: #002200;">&#93;</span> selector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>request<span style="color: #002200;">:</span>completeBlock<span style="color: #002200;">:</span>errorBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> swizzleClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>RequestPopularCoachesPassMock class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    __block <span style="color: #a61390;">BOOL</span> hasCalledBack <span style="color: #002200;">=</span> <span style="color: #a61390;">NO</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Test</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>endpoint <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@?per_page=6&amp;amp;page=1&amp;amp;popular=true&quot;</span>, kCoachesEndpoint<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>JSONLoader sharedJSONLoader<span style="color: #002200;">&#93;</span> loadCollectionFromEndpoint<span style="color: #002200;">:</span>endpoint successBlock<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>collection<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>coaches <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>collection valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;coaches&quot;</span><span style="color: #002200;">&#93;</span>;
        assertThat<span style="color: #002200;">&#40;</span>coaches, hasCountOf<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">6</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>; 
        <span style="color: #a61390;">int</span> i <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>;
        <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>coach <span style="color: #a61390;">in</span> coaches<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            STAssertTrue<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>coach isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDictionary</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Incorrect class&quot;</span><span style="color: #002200;">&#41;</span>;
            assertThat<span style="color: #002200;">&#40;</span>coach, equalTo<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>popularCoaches objectAtIndex<span style="color: #002200;">:</span>i<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// popularCoaches defined elsewhere with expected data</span>
            <span style="color: #002200;">++</span>i;
        <span style="color: #002200;">&#125;</span>
        assertThat<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>collection valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;per_page&quot;</span><span style="color: #002200;">&#93;</span>, equalToInt<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">6</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
        assertThat<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>collection valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;page&quot;</span><span style="color: #002200;">&#93;</span>, equalToInt<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
        assertThat<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>collection valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;total&quot;</span><span style="color: #002200;">&#93;</span>, equalToInt<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">11</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
        assertThat<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>collection valueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;total_pages&quot;</span><span style="color: #002200;">&#93;</span>, equalToInt<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
        hasCalledBack <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
    <span style="color: #002200;">&#125;</span> failBlock<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, <span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
        STFail<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Unexpected error returned&quot;</span><span style="color: #002200;">&#41;</span>;
        hasCalledBack <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
    <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// see http://drewsmitscode.posterous.com/testing-asynchronous-code-in-objective-c</span>
    <span style="color: #400080;">NSDate</span> <span style="color: #002200;">*</span>loopUntil <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDate</span> dateWithTimeIntervalSinceNow<span style="color: #002200;">:</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">while</span> <span style="color: #002200;">&#40;</span>hasCalledBack <span style="color: #002200;">==</span> <span style="color: #a61390;">NO</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSRunLoop</span> currentRunLoop<span style="color: #002200;">&#93;</span> runMode<span style="color: #002200;">:</span>NSDefaultRunLoopMode beforeDate<span style="color: #002200;">:</span>loopUntil<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
    swizzler <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>You can use any class to provide an implementation of the replacement method. This approach allows you can return various responses from your HTTP request. Here is one that returns the expected payload that is read from a file.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> RequestPopularCoachesPassMock <span style="color: #002200;">:</span> <span style="color: #400080;">NSObject</span>
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>request<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>requestUrl completeBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>completeBlock_t<span style="color: #002200;">&#41;</span>completeBlock errorBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>errorBlock_t<span style="color: #002200;">&#41;</span>errorBlock;
&nbsp;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> RequestPopularCoachesPassMock
&nbsp;
<span style="color: #11740a; font-style: italic;">// Swizzled method</span>
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>request<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>requestUrl completeBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>completeBlock_t<span style="color: #002200;">&#41;</span>completeBlock errorBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>errorBlock_t<span style="color: #002200;">&#41;</span>errorBlock
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>completeBlock<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>FileReader dataWithContentsOfBundleFile<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;popularCoaches.json&quot;</span><span style="color: #002200;">&#93;</span>;
        completeBlock<span style="color: #002200;">&#40;</span>data<span style="color: #002200;">&#41;</span>;        
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<h2>Conclusion</h2>
<p>In this blog post I have demonstrated how to use the Objective-C runtime dynamic method replacement technique known as *method swizzling* to assist with unit testing in a situation where there is a 3rd party web service that I want to mock. This technique can be used during development to assist with integrating of an iOS app with a web service. It helps speed up development and prototyping. It can also be applied during development in the normal running of your app if you want to mock out portions of or all of a web service.</p>
<!-- Start Sociable --><div class="sociable"><ul class='clearfix'></ul><div onMouseout="fixOnMouseOut(this,event,'post-3741')" id="sociable-post-3741" style="display:none;">   

    <div style="top: auto; left: auto; display: block;" id="sociable">



		<div class="popup">

			<div class="content">

				<ul><li style="heigth:32px;width:32px"><a title="Facebook" class="option1_32" style="background-position:-96px 0px" rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;t=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development"></a></li><li style="heigth:32px;width:32px"><a title="Myspace" class="option1_32" style="background-position:0px -32px" rel="nofollow" target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;t=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development"></a></li><li style="heigth:32px;width:32px"><a title="Twitter" class="option1_32" style="background-position:-288px -32px" rel="nofollow" target="_blank" href="http://twitter.com/intent/tweet?text=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development%20-%20http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F%20  SHARETAG"></a></li><li style="heigth:32px;width:32px"><a title="LinkedIn" class="option1_32" style="background-position:-288px 0px" rel="nofollow" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;title=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development&amp;source=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials&amp;summary=Introduction%0D%0AIn%20this%20blog%20post%20I%20will%20demonstrate%20how%20to%20mock%20HTTP%20requests%20using%C2%A0an%20Objective-C%20runtime%20dynamic%20method%20replacement%20technique%20known%20as%20method%20swizzling.%20I%20will%20show%20how%20this%20can%20be%20used%20in%20tandem%20with%20some%20unit%20test%20technologies%20to%20"></a></li><li style="heigth:32px;width:32px"><a title="Delicious" class="option1_32" style="background-position:-32px 0px" rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;title=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development&amp;notes=Introduction%0D%0AIn%20this%20blog%20post%20I%20will%20demonstrate%20how%20to%20mock%20HTTP%20requests%20using%C2%A0an%20Objective-C%20runtime%20dynamic%20method%20replacement%20technique%20known%20as%20method%20swizzling.%20I%20will%20show%20how%20this%20can%20be%20used%20in%20tandem%20with%20some%20unit%20test%20technologies%20to%20"></a></li><li style="heigth:32px;width:32px"><a title="Digg" class="option1_32" style="background-position:-64px 0px" rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;title=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development&amp;bodytext=Introduction%0D%0AIn%20this%20blog%20post%20I%20will%20demonstrate%20how%20to%20mock%20HTTP%20requests%20using%C2%A0an%20Objective-C%20runtime%20dynamic%20method%20replacement%20technique%20known%20as%20method%20swizzling.%20I%20will%20show%20how%20this%20can%20be%20used%20in%20tandem%20with%20some%20unit%20test%20technologies%20to%20"></a></li><li style="heigth:32px;width:32px"><a title="Reddit" class="option1_32" style="background-position:-128px -32px" rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;title=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development"></a></li><li style="heigth:32px;width:32px"><a title="StumbleUpon" class="option1_32" style="background-position:-224px -32px" rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&title=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development"></a></li><li style="heigth:32px;width:32px"><a title="Google Bookmarks" class="option1_32" style="background-position:-192px 0px" rel="nofollow" target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;title=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development&amp;annotation=Introduction%0D%0AIn%20this%20blog%20post%20I%20will%20demonstrate%20how%20to%20mock%20HTTP%20requests%20using%C2%A0an%20Objective-C%20runtime%20dynamic%20method%20replacement%20technique%20known%20as%20method%20swizzling.%20I%20will%20show%20how%20this%20can%20be%20used%20in%20tandem%20with%20some%20unit%20test%20technologies%20to%20"></a></li><li style="heigth:32px;width:32px"><a title="HackerNews" class="option1_32" style="background-position:-256px 0px" rel="nofollow" target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;t=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development"></a></li><li style="heigth:32px;width:32px"><a title="MSNReporter" class="option1_32" style="background-position:-352px 0px" rel="nofollow" target="_blank" href="http://reporter.es.msn.com/?fn=contribute&amp;Title=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development&amp;URL=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;cat_id=6&amp;tag_id=31&amp;Remark=Introduction%0D%0AIn%20this%20blog%20post%20I%20will%20demonstrate%20how%20to%20mock%20HTTP%20requests%20using%C2%A0an%20Objective-C%20runtime%20dynamic%20method%20replacement%20technique%20known%20as%20method%20swizzling.%20I%20will%20show%20how%20this%20can%20be%20used%20in%20tandem%20with%20some%20unit%20test%20technologies%20to%20"></a></li><li style="heigth:32px;width:32px"><a title="BlinkList" class="option1_32" style="background-position:0px 0px" rel="nofollow" target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;Title=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development"></a></li><li style="heigth:32px;width:32px"><a title="Sphinn" class="option1_32" style="background-position:-192px -32px" rel="nofollow" target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F"></a></li><li style="heigth:32px;width:32px"><a title="Posterous" class="option1_32" style="background-position:-64px -32px" rel="nofollow" target="_blank" href="http://posterous.com/share?linkto=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;title=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development&amp;selection=Introduction%0D%0AIn%20this%20blog%20post%20I%20will%20demonstrate%20how%20to%20mock%20HTTP%20requests%20using%C2%A0an%20Objective-C%20runtime%20dynamic%20method%20replacement%20technique%20known%20as%20method%20swizzling.%20I%20will%20show%20how%20this%20can%20be%20used%20in%20tandem%20with%20some%20unit%20test%20technologies%20to%20"></a></li><li style="heigth:32px;width:32px"><a title="Tumblr" class="option1_32" style="background-position:-256px -32px" rel="nofollow" target="_blank" href="http://www.tumblr.com/share?v=3&amp;u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;t=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development&amp;s=Introduction%0D%0AIn%20this%20blog%20post%20I%20will%20demonstrate%20how%20to%20mock%20HTTP%20requests%20using%C2%A0an%20Objective-C%20runtime%20dynamic%20method%20replacement%20technique%20known%20as%20method%20swizzling.%20I%20will%20show%20how%20this%20can%20be%20used%20in%20tandem%20with%20some%20unit%20test%20technologies%20to%20"></a></li><li style="heigth:32px;width:32px"><a title="email" class="option1_32" style="background-position:-160px 0px" rel="nofollow" target="_blank" href="https://mail.google.com/mail/?view=cm&fs=1&to&su=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development&body=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&ui=2&tf=1&shva=1"></a></li><li style="heigth:32px;width:32px"><a title="Google Reader" class="option1_32" style="background-position:-224px 0px" rel="nofollow" target="_blank" href="http://www.google.com/reader/link?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;title=Using%20Method-Swizzling%20to%20help%20with%20Test%20Driven%20Development&amp;srcURL=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F08%2F08%2Fusing-method-swizzling-to-help-with-test-driven-development%2F&amp;srcTitle=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials"></a></li><li style="heigth:32px;width:32px"><a class="option1_32" style="cursor:pointer;background-position:-128px 0px" rel="nofollow" title="Add to favorites - doesn't work in Chrome"  onClick="javascript:AddToFavorites();"></a></li><li style="heigth:32px;width:32px"><a style="cursor:poainter" rel="nofollow"   onMouseOver="more(this,'post-3741')"><img style='margin-top:9px' src='/wp-content/plugins/sociable/images/more.png'></a></li></ul>			

			</div>        

		  <a style="cursor:pointer" onclick="hide_sociable('post-3741',true)" class="close">

		  <img onclick="hide_sociable('post-3741',true)" title="close" src="/wp-content/plugins/sociable/images/closelabel.png">

		  </a>

		</div>

	</div> 

  </div></div><div class='sociable' style='float:none'><ul class='clearfix'><li id="Twitter_Counter"><a href="https://twitter.com/share" data-text="Using Method-Swizzling to help with Test Driven Development - http://icodeblog.com/2012/08/08/using-method-swizzling-to-help-with-test-driven-development/" data-url="http://icodeblog.com/2012/08/08/using-method-swizzling-to-help-with-test-driven-development/" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></li><li id="Facebook_Counter"><iframe src="http://www.facebook.com/plugins/like.php?href=http://icodeblog.com/2012/08/08/using-method-swizzling-to-help-with-test-driven-development/&send=false&layout=button_count&show_faces=false&action=like&colorscheme=light&font" scrolling="no" frameborder="0" style="border:none; overflow:hidden;height:32px;width:100px" allowTransparency="true"></iframe></li><li id="Google_p"><g:plusone annotation="bubble" href="/2012/08/08/using-method-swizzling-to-help-with-test-driven-development/" size="medium"></g:plusone></li><li id="LinkedIn_Counter"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="http://icodeblog.com/2012/08/08/using-method-swizzling-to-help-with-test-driven-development/" data-counter="right"></script></li></ul></div><!-- End Sociable -->]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2012/08/08/using-method-swizzling-to-help-with-test-driven-development/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to Add GPS to Your iOS App &#8211; Part 1</title>
		<link>http://icodeblog.com/2012/06/04/how-to-add-gps-to-your-ios-app-part-1/</link>
		<comments>http://icodeblog.com/2012/06/04/how-to-add-gps-to-your-ios-app-part-1/#comments</comments>
		<pubDate>Mon, 04 Jun 2012 21:33:11 +0000</pubDate>
		<dc:creator><![CDATA[Shawn Grimes]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[beginner]]></category>
		<category><![CDATA[CoreLocation]]></category>
		<category><![CDATA[GPS]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPhone Coding]]></category>
		<category><![CDATA[iphone dev]]></category>
		<category><![CDATA[iphone development]]></category>
		<category><![CDATA[iphone programming]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=3690</guid>
		<description><![CDATA[
In Part 1 of this series, I will introduce you to the very basics of CoreLocation services and getting the location of the device currently being used.
About CoreLocation
The CoreLocation framework provides your app with the ability to get a device&#8217;s current location, provided the user of the device has granted your app access to that information.
Location services are provided in two major ways using this framework:

Standard Location Services&#8211; This service provides the most accurate location information using a variety of  ...]]></description>
				<content:encoded><![CDATA[<p><center><img src="http://img.skitch.com/20120604-drip3tee432eccbfhsdkrpwhbr.jpg" alt="CoreLocation Graphic" /></center></p>
<blockquote><p>In Part 1 of this series, I will introduce you to the very basics of CoreLocation services and getting the location of the device currently being used.</p></blockquote>
<h2>About CoreLocation</h2>
<p>The CoreLocation framework provides your app with the ability to get a device&#8217;s current location, provided the user of the device has granted your app access to that information.</p>
<p>Location services are provided in two major ways using this framework:</p>
<ol>
<li><strong>Standard Location Services</strong>&#8211; This service provides the most accurate location information using a variety of methods including celluar, wifi, and GPS.
<ul>
<li>Most accurate.</li>
<li>Consumes the most power and can take a longer time to acquire.</li>
<li>Can only be used when your application is in the foreground.</li>
</ul>
</li>
<li><strong>Significant Change Location Services</strong>&#8211; This service uses cellular data to determine a general idea of where the device is located.
<ul>
<li>Fastest and uses the least amount of power to determine the location.</li>
<li>Can also be used to notify your app when a significant change in the location has occurred even if your app is not in focus.</li>
</ul>
</li>
</ol>
<h2>Project Files:</h2>
<p>You can download the project files at this github repository: <a href="http://github.com/shawngrimes/Location-and-Map-Sample">http://github.com/shawngrimes/Location-and-Map-Sample</a></p>
<h2>Adding Location Frameworks</h2>
<p>The first step to adding location services to your project is to add the CoreLocation framework.</p>
<div class="thumbnail" align="center"><a href="http://skitch.com/shawnegrimes/86jyp/link-binary-with-libraries"><img src="http://img.skitch.com/20120603-d7w4x5fyueprskt33g5xet7a1n.preview.jpg" alt="Link Binary With Libraries" /></a></div>
<ol>
<li>Select your target and go to the &#8220;Build Phases&#8221; tab.</li>
<li>Click the &#8220;+&#8221; button under &#8220;Link Binary With Libraries&#8221;</li>
<li>Select the CoreLocation framework and click &#8220;Add&#8221;</li>
</ol>
<div class="thumbnail" align="center"><a href="http://skitch.com/shawnegrimes/86je5/add-core-location-framework"><img src="http://img.skitch.com/20120603-gby2hyh3mtsfax86u5ht39491r.preview.jpg" alt="Add Core Location Framework" /></a></div>
<h2>Location Manager</h2>
<p>With location services, you create an instance of CLLocationManager. There is usually one instance of this per app so I feel a good place for this is in the App Delegate and then each view can access the current location from the App Delegate.</p>
<p>To start, open your App Delegate header file:</p>
<ol>
<li>Add <code>#import &lt;CoreLocation/CoreLocation.h&gt;</code> to the top</li>
<li>Specify that your app delegate complies with the Core Location Delegate protocol by changing your <code>@interface</code> line with <code>@interface CFAAppDelegate : UIResponder &lt;UIApplicationDelegate, CLLocationManagerDelegate&gt;</code></li>
<li>Specify a CLLocationManager property by adding <code>@property (strong, nonatomic) CLLocationManager *locationManager</code> right before the <code>@end</code> statement.</li>
</ol>
<p>Your App Delegate header file should now look similar to the following:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &amp;lt;UIKit/UIKit.h&amp;gt;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">//Add Location Framework</span>
<span style="color: #6e371a;">#import &amp;lt;CoreLocation/CoreLocation.h&amp;gt;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">//Specify this app delegate complies with the location manager delegate</span>
<span style="color: #a61390;">@interface</span> CFAAppDelegate <span style="color: #002200;">:</span> UIResponder <span style="color: #002200;">&amp;</span>lt;UIApplicationDelegate, CLLocationManagerDelegate<span style="color: #002200;">&amp;</span>gt;
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>strong, nonatomic<span style="color: #002200;">&#41;</span> UIWindow <span style="color: #002200;">*</span>window;
&nbsp;
<span style="color: #11740a; font-style: italic;">//Add a location manager property to this app delegate</span>
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>strong, nonatomic<span style="color: #002200;">&#41;</span> CLLocationManager <span style="color: #002200;">*</span>locationManager;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<h2>Creating The Location Manager Object</h2>
<p>Switch over to the App Delegate implementation file (.m), and we are going to create our location manager object. The first thing we should do, since we created it as a property of our app delegate, is synthesize the property so add <code>@synthesize locationManager=_locationManager;</code> under the line that reads <code>@synthesize window = _window;</code>.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;CFAAppDelegate.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> CFAAppDelegate
&nbsp;
<span style="color: #a61390;">@synthesize</span> window <span style="color: #002200;">=</span> _window;
<span style="color: #a61390;">@synthesize</span> locationManager<span style="color: #002200;">=</span>_locationManager;</pre></td></tr></table></div>

<p>Now that our property is synthesized, we can create the object. I usually create it in the method <code>application didFinishLaunchingWithOptions:</code>. A Location Manager object is created similar to any other object but there are three important properties you should set after you have alloc&#8217;d/init&#8217;d.</p>
<ol>
<li><strong>.purpose</strong> &#8211; The purpose property is displayed to the user of your app when they are prompted to allow your app to use their location. It gives you a chance to explain what your app is going to do with their location information.</li>
<li><strong>.desiredAccuracy</strong> &#8211; The desired accuracy property allows you to tell the device how accurate you would like the location information to be. This should be set based on your application&#8217;s needs. Don&#8217;t set this property to <code>kCLLocationAccuracyBest</code> if you only need to know what city they are in. <em>NOTE: This is the &#8220;desired&#8221; accuracy, it is not guaranteed. The device will determine the best available information and provide it to you but you are not, however, guaranteed any level of accuracy.</em></li>
<li><strong>.distanceFilter</strong> &#8211; The distance filter property tells the location manager how far a device needs to move (horizontally vs. an altitude change) before triggering a new location event. It is measured in meters. You can set the property to <code>kCLDistanceFilterNone</code> to be notified of all events (this is also the default value).</li>
</ol>
<p>The completed creation of our location manage looks like this:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>application<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIApplication <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>application didFinishLaunchingWithOptions<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>launchOptions
<span style="color: #002200;">&#123;</span>
    self.window <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIWindow alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIScreen mainScreen<span style="color: #002200;">&#93;</span> bounds<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #11740a; font-style: italic;">// Override point for customization after application launch.</span>
    self.window.backgroundColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIColor whiteColor<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>self.window makeKeyAndVisible<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span>self.locationManager<span style="color: #002200;">==</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#123;</span>
        _locationManager<span style="color: #002200;">=</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CLLocationManager alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
        <span style="color: #11740a; font-style: italic;">//I'm using ARC with this project so no need to release</span>
&nbsp;
        _locationManager.delegate<span style="color: #002200;">=</span>self;
        _locationManager.purpose <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;We will try to tell you where you are if you get lost&quot;</span>;
        _locationManager.desiredAccuracy<span style="color: #002200;">=</span>kCLLocationAccuracyBest;
        _locationManager.distanceFilter<span style="color: #002200;">=</span><span style="color: #2400d9;">500</span>;
        self.locationManager<span style="color: #002200;">=</span>_locationManager;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">YES</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>If you run this now, you should not notice any change in the way your application runs, you also won&#8217;t start receiving location information just yet. That comes next&#8230;</p>
<h2>Starting Location Services</h2>
<p>Now that we have our location manager configured, we want to start getting the location. To start the standard location service, you should first check to make sure that location services are enabled. This is done with a simple call to <code>[CLLocationManager locationServicesEnabled]</code> so after we set up our location manager above and before the <code>return YES;</code>, add the following code:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">    <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>CLLocationManager locationServicesEnabled<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>self.locationManager startUpdatingLocation<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<blockquote><p>NOTE: If location services are not enabled and you start updating location services, the user will be prompted to enable location services. This could be annoying to the end user if they have to answer &#8220;No&#8221; every time your app launches.</p></blockquote>
<p>If you run your app now, you will notice that the user is prompted to enable location services (and it will include the message from the <code>.prompt</code> property of our location manager object).</p>
<div class="thumbnail" align="center"><a href="http://skitch.com/shawnegrimes/86idb/enablelocationservicesprompt"><img src="http://img.skitch.com/20120605-ke3m4ipx1cj2p9pprstkcdcrdn.preview.jpg" alt="EnableLocationServicesPrompt" /></a></div>
<h2>Receiving Location Changes</h2>
<p>We&#8217;ve started location services, but now we need to start receiving updates to location changes. This is all done through the <code>CLLocationManagerDelegate</code> protocol. There are a number of available methods to implement for this delegate but the three most important are probably:</p>
<ol>
<li>– locationManager:didUpdateToLocation:fromLocation:</li>
<li>– locationManager:didFailWithError:</li>
<li>– locationManager:didChangeAuthorizationStatus:</li>
</ol>
<h2>– locationManager:didUpdateToLocation:fromLocation:</h2>
<p>Let&#8217;s start with receiving an update in location and how to handle that. In our App Delegate implementation file (.m), add the following method placeholder below the <code>@synthesize …</code> statements and above <code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions</code> method:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>locationManager<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CLLocationManager <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>manager didUpdateToLocation<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CLLocation <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>newLocation fromLocation<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CLLocation <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>oldLocation<span style="color: #002200;">&#123;</span>
&nbsp;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>One of the first things I like to do is check the timestamp of the newLocation detected. When you first start updating location services, the location manager will receive the last known location of the device, this could be hours or days old depending on the last time location services were used. In my apps, I like to make sure that I have a recent location. This following code will only use a location that has been found in the last 15.0 seconds:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">    <span style="color: #400080;">NSDate</span><span style="color: #002200;">*</span> eventDate <span style="color: #002200;">=</span> newLocation.timestamp;
    NSTimeInterval howRecent <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>eventDate timeIntervalSinceNow<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">abs</span><span style="color: #002200;">&#40;</span>howRecent<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;</span>lt; <span style="color: #2400d9;">15.0</span><span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">//Location timestamp is within the last 15.0 seconds, let's use it!</span>
    <span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>The next check that I like to perform is to see how accurate the newLocation is. This can be done by looking at the <code>.horizontalAccuracy</code> property. This property tells you how accurate your location information is. As I stated above, you can request to have very accurate locations but you are not guaranteed it. In the illustration below, the newLocation.coordinate is the location the device thinks it is, but in truth the orange circle of the .horizontalAccuracy says that it could be anywhere in that circle.</p>
<div class="thumbnail" align="center"><a href="https://skitch.com/shawnegrimes/86kp3/horizontalaccuracy"><img src="https://img.skitch.com/20120603-enfpceaw8jgsqw1hieenx48jmj.preview.jpg" alt="horizontalAccuracy" /></a></div>
<p>Your application&#8217;s need will determine how accurate of a location you need. Again, if you just need the city the user is in, you won&#8217;t need it to be as accurate as if you were trying to find something within walking distance. In the code below, I have set my accuracy threshold to 35.0 meters. This is pretty broad but I have found that it works well indoors as well as out. Insert the following code right after the comment <code>//Location timestamp is within the last 15.0 seconds, let's use it!</code></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">        <span style="color: #11740a; font-style: italic;">//Location timestamp is within the last 15.0 seconds, let's use it!</span>
        <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span>newLocation.horizontalAccuracy<span style="color: #002200;">&amp;</span>lt;<span style="color: #2400d9;">35.0</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#123;</span>
            <span style="color: #11740a; font-style: italic;">//Location seems pretty accurate, let's use it!</span>
            NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;latitude %+.6f, longitude %+.6f<span style="color: #2400d9;">\n</span>&quot;</span>,
                  newLocation.coordinate.latitude,
                  newLocation.coordinate.longitude<span style="color: #002200;">&#41;</span>;
            NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Horizontal Accuracy:%f&quot;</span>, newLocation.horizontalAccuracy<span style="color: #002200;">&#41;</span>;
&nbsp;
            <span style="color: #11740a; font-style: italic;">//Optional: turn off location services once we've gotten a good location</span>
            <span style="color: #002200;">&#91;</span>manager stopUpdatingLocation<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>The code above will print the new location to the console and then turn off location services. This is an optional step but if you don&#8217;t need location services anymore, it&#8217;s a smart thing to turn them off to conserve your user&#8217;s battery.</p>
<p>This is what our complete delegate method looks like:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>locationManager<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CLLocationManager <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>manager didUpdateToLocation<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CLLocation <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>newLocation fromLocation<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CLLocation <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>oldLocation<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSDate</span><span style="color: #002200;">*</span> eventDate <span style="color: #002200;">=</span> newLocation.timestamp;
    NSTimeInterval howRecent <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>eventDate timeIntervalSinceNow<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">abs</span><span style="color: #002200;">&#40;</span>howRecent<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;</span>lt; <span style="color: #2400d9;">15.0</span><span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">//Location timestamp is within the last 15.0 seconds, let's use it!</span>
        <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span>newLocation.horizontalAccuracy<span style="color: #002200;">&amp;</span>lt;<span style="color: #2400d9;">35.0</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#123;</span>
            <span style="color: #11740a; font-style: italic;">//Location seems pretty accurate, let's use it!</span>
            NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;latitude %+.6f, longitude %+.6f<span style="color: #2400d9;">\n</span>&quot;</span>,
                  newLocation.coordinate.latitude,
                  newLocation.coordinate.longitude<span style="color: #002200;">&#41;</span>;
            NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Horizontal Accuracy:%f&quot;</span>, newLocation.horizontalAccuracy<span style="color: #002200;">&#41;</span>;
&nbsp;
            <span style="color: #11740a; font-style: italic;">//Optional: turn off location services once we've gotten a good location</span>
            <span style="color: #002200;">&#91;</span>manager stopUpdatingLocation<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Now we can run the project again. If you didn&#8217;t authorize the app to use location services before, go ahead and do that now. We haven&#8217;t done anything with the location at this point except print it out to the console. If you don&#8217;t know how to see the console, make sure Xcode is the active window (NOT the simulator) and press ⌘⇧C</p>
<p>If you are running the project on the simulator and not a device, you may not see any results in the console window. This is because the simulator does not have location services turned on by default. You can simulate a location by selecting the location services simulation in the console window:</p>
<div class="thumbnail" align="center"><a href="http://skitch.com/shawnegrimes/86typ/simulate-location"><img src="http://img.skitch.com/20120604-b359j7crjba8wctd1gje5kk112.preview.jpg" alt="Simulate Location" /></a></div>
<p>You can also simulate a location in the Simulator by using the Debug menu.</p>
<div class="thumbnail" align="center"><a href="https://skitch.com/shawnegrimes/86tn4/simulator-location-services"><img src="https://img.skitch.com/20120604-qxs23ikjy6qufjpwpg72fuewk9.preview.jpg" alt="Simulator Location Services" /></a></div>
<p>Once a location has been selected, you may need to restart the app to get the new location to show in the console window:</p>
<div class="thumbnail" align="center"><a href="https://skitch.com/shawnegrimes/86trw/location-in-console"><img src="https://img.skitch.com/20120604-ddt5unstdmea3i58ddxsgfgih8.preview.jpg" alt="Location In Console" /></a></div>
<p>Because we built the location manager into the App Delegate, you can access the device&#8217;s current location anywhere in your code by including the AppDelegate header file (.h) in your view controller&#8217;s implementation file (.m):</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;CFAAppDelegate.h&quot;</span></pre></td></tr></table></div>

<p>Then whenever you need to access the location, you can use the following bit of code:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">//Make sure location services are enabled before requesting the location</span>
<span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>CLLocationManager locationServicesEnabled<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#123;</span>
&nbsp;
    CFAAppDelegate <span style="color: #002200;">*</span>appDelegate<span style="color: #002200;">=</span><span style="color: #002200;">&#40;</span>CFAAppDelegate <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>UIApplication sharedApplication<span style="color: #002200;">&#93;</span>.delegate;
    CLLocation <span style="color: #002200;">*</span>currentLocation<span style="color: #002200;">=</span>appDelegate.locationManager.location;
&nbsp;
    <span style="color: #11740a; font-style: italic;">//Do what you want with the location...</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<blockquote><p><strong>About: Shawn Grimes</strong><br />
Shawn is a mobile app developer for <a href="http://elctech.com/">ELC Technologies</a>. He is a co-author of the book, <a href="http://www.amazon.com/gp/product/1430240059/ref=as_li_ss_tl?ie=UTF8&amp;tag=charmtrave-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1430240059">iOS 5 Recipes: A Problem-Solution Approach (Recipes Apress)</a>. You can follow him on twitter <a href="https://twitter.com/#!/shawng">@shawng</a>. Shawn also works with high school students to teach them app development skills through the <a href="http://www.appliedclub.org">APPlied Club</a> Program.</p></blockquote>
<p>UIKit/UIKit.hp</p>
<!-- Start Sociable --><div class="sociable"><ul class='clearfix'></ul><div onMouseout="fixOnMouseOut(this,event,'post-3690')" id="sociable-post-3690" style="display:none;">   

    <div style="top: auto; left: auto; display: block;" id="sociable">



		<div class="popup">

			<div class="content">

				<ul><li style="heigth:32px;width:32px"><a title="Facebook" class="option1_32" style="background-position:-96px 0px" rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;t=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201"></a></li><li style="heigth:32px;width:32px"><a title="Myspace" class="option1_32" style="background-position:0px -32px" rel="nofollow" target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;t=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201"></a></li><li style="heigth:32px;width:32px"><a title="Twitter" class="option1_32" style="background-position:-288px -32px" rel="nofollow" target="_blank" href="http://twitter.com/intent/tweet?text=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201%20-%20http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F%20  SHARETAG"></a></li><li style="heigth:32px;width:32px"><a title="LinkedIn" class="option1_32" style="background-position:-288px 0px" rel="nofollow" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;title=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201&amp;source=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials&amp;summary=%0D%0AIn%20Part%201%20of%20this%20series%2C%20I%20will%20introduce%20you%20to%20the%20very%20basics%20of%20CoreLocation%20services%20and%20getting%20the%20location%20of%20the%20device%20currently%20being%20used.%0D%0AAbout%20CoreLocation%0D%0AThe%20CoreLocation%20framework%20provides%20your%20app%20with%20the%20ability%20to%20get%20a%20devi"></a></li><li style="heigth:32px;width:32px"><a title="Delicious" class="option1_32" style="background-position:-32px 0px" rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;title=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201&amp;notes=%0D%0AIn%20Part%201%20of%20this%20series%2C%20I%20will%20introduce%20you%20to%20the%20very%20basics%20of%20CoreLocation%20services%20and%20getting%20the%20location%20of%20the%20device%20currently%20being%20used.%0D%0AAbout%20CoreLocation%0D%0AThe%20CoreLocation%20framework%20provides%20your%20app%20with%20the%20ability%20to%20get%20a%20devi"></a></li><li style="heigth:32px;width:32px"><a title="Digg" class="option1_32" style="background-position:-64px 0px" rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;title=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201&amp;bodytext=%0D%0AIn%20Part%201%20of%20this%20series%2C%20I%20will%20introduce%20you%20to%20the%20very%20basics%20of%20CoreLocation%20services%20and%20getting%20the%20location%20of%20the%20device%20currently%20being%20used.%0D%0AAbout%20CoreLocation%0D%0AThe%20CoreLocation%20framework%20provides%20your%20app%20with%20the%20ability%20to%20get%20a%20devi"></a></li><li style="heigth:32px;width:32px"><a title="Reddit" class="option1_32" style="background-position:-128px -32px" rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;title=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201"></a></li><li style="heigth:32px;width:32px"><a title="StumbleUpon" class="option1_32" style="background-position:-224px -32px" rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&title=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201"></a></li><li style="heigth:32px;width:32px"><a title="Google Bookmarks" class="option1_32" style="background-position:-192px 0px" rel="nofollow" target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;title=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201&amp;annotation=%0D%0AIn%20Part%201%20of%20this%20series%2C%20I%20will%20introduce%20you%20to%20the%20very%20basics%20of%20CoreLocation%20services%20and%20getting%20the%20location%20of%20the%20device%20currently%20being%20used.%0D%0AAbout%20CoreLocation%0D%0AThe%20CoreLocation%20framework%20provides%20your%20app%20with%20the%20ability%20to%20get%20a%20devi"></a></li><li style="heigth:32px;width:32px"><a title="HackerNews" class="option1_32" style="background-position:-256px 0px" rel="nofollow" target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;t=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201"></a></li><li style="heigth:32px;width:32px"><a title="MSNReporter" class="option1_32" style="background-position:-352px 0px" rel="nofollow" target="_blank" href="http://reporter.es.msn.com/?fn=contribute&amp;Title=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201&amp;URL=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;cat_id=6&amp;tag_id=31&amp;Remark=%0D%0AIn%20Part%201%20of%20this%20series%2C%20I%20will%20introduce%20you%20to%20the%20very%20basics%20of%20CoreLocation%20services%20and%20getting%20the%20location%20of%20the%20device%20currently%20being%20used.%0D%0AAbout%20CoreLocation%0D%0AThe%20CoreLocation%20framework%20provides%20your%20app%20with%20the%20ability%20to%20get%20a%20devi"></a></li><li style="heigth:32px;width:32px"><a title="BlinkList" class="option1_32" style="background-position:0px 0px" rel="nofollow" target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;Title=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201"></a></li><li style="heigth:32px;width:32px"><a title="Sphinn" class="option1_32" style="background-position:-192px -32px" rel="nofollow" target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F"></a></li><li style="heigth:32px;width:32px"><a title="Posterous" class="option1_32" style="background-position:-64px -32px" rel="nofollow" target="_blank" href="http://posterous.com/share?linkto=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;title=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201&amp;selection=%0D%0AIn%20Part%201%20of%20this%20series%2C%20I%20will%20introduce%20you%20to%20the%20very%20basics%20of%20CoreLocation%20services%20and%20getting%20the%20location%20of%20the%20device%20currently%20being%20used.%0D%0AAbout%20CoreLocation%0D%0AThe%20CoreLocation%20framework%20provides%20your%20app%20with%20the%20ability%20to%20get%20a%20devi"></a></li><li style="heigth:32px;width:32px"><a title="Tumblr" class="option1_32" style="background-position:-256px -32px" rel="nofollow" target="_blank" href="http://www.tumblr.com/share?v=3&amp;u=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;t=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201&amp;s=%0D%0AIn%20Part%201%20of%20this%20series%2C%20I%20will%20introduce%20you%20to%20the%20very%20basics%20of%20CoreLocation%20services%20and%20getting%20the%20location%20of%20the%20device%20currently%20being%20used.%0D%0AAbout%20CoreLocation%0D%0AThe%20CoreLocation%20framework%20provides%20your%20app%20with%20the%20ability%20to%20get%20a%20devi"></a></li><li style="heigth:32px;width:32px"><a title="email" class="option1_32" style="background-position:-160px 0px" rel="nofollow" target="_blank" href="https://mail.google.com/mail/?view=cm&fs=1&to&su=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201&body=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&ui=2&tf=1&shva=1"></a></li><li style="heigth:32px;width:32px"><a title="Google Reader" class="option1_32" style="background-position:-224px 0px" rel="nofollow" target="_blank" href="http://www.google.com/reader/link?url=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;title=How%20to%20Add%20GPS%20to%20Your%20iOS%20App%20-%20Part%201&amp;srcURL=http%3A%2F%2Fwww.icodeblog.com%2F2012%2F06%2F04%2Fhow-to-add-gps-to-your-ios-app-part-1%2F&amp;srcTitle=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials"></a></li><li style="heigth:32px;width:32px"><a class="option1_32" style="cursor:pointer;background-position:-128px 0px" rel="nofollow" title="Add to favorites - doesn't work in Chrome"  onClick="javascript:AddToFavorites();"></a></li><li style="heigth:32px;width:32px"><a style="cursor:poainter" rel="nofollow"   onMouseOver="more(this,'post-3690')"><img style='margin-top:9px' src='/wp-content/plugins/sociable/images/more.png'></a></li></ul>			

			</div>        

		  <a style="cursor:pointer" onclick="hide_sociable('post-3690',true)" class="close">

		  <img onclick="hide_sociable('post-3690',true)" title="close" src="/wp-content/plugins/sociable/images/closelabel.png">

		  </a>

		</div>

	</div> 

  </div></div><div class='sociable' style='float:none'><ul class='clearfix'><li id="Twitter_Counter"><a href="https://twitter.com/share" data-text="How to Add GPS to Your iOS App - Part 1 - http://icodeblog.com/2012/06/04/how-to-add-gps-to-your-ios-app-part-1/" data-url="http://icodeblog.com/2012/06/04/how-to-add-gps-to-your-ios-app-part-1/" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></li><li id="Facebook_Counter"><iframe src="http://www.facebook.com/plugins/like.php?href=http://icodeblog.com/2012/06/04/how-to-add-gps-to-your-ios-app-part-1/&send=false&layout=button_count&show_faces=false&action=like&colorscheme=light&font" scrolling="no" frameborder="0" style="border:none; overflow:hidden;height:32px;width:100px" allowTransparency="true"></iframe></li><li id="Google_p"><g:plusone annotation="bubble" href="/2012/06/04/how-to-add-gps-to-your-ios-app-part-1/" size="medium"></g:plusone></li><li id="LinkedIn_Counter"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="http://icodeblog.com/2012/06/04/how-to-add-gps-to-your-ios-app-part-1/" data-counter="right"></script></li></ul></div><!-- End Sociable -->]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2012/06/04/how-to-add-gps-to-your-ios-app-part-1/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using XCode 4 Snippets</title>
		<link>http://icodeblog.com/2011/12/06/using-xcode-4-snippets/</link>
		<comments>http://icodeblog.com/2011/12/06/using-xcode-4-snippets/#comments</comments>
		<pubDate>Tue, 06 Dec 2011 23:02:06 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[beginner]]></category>
		<category><![CDATA[snippets]]></category>
		<category><![CDATA[xcode4]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=3658</guid>
		<description><![CDATA[Recently, I came across <a href="http://nearthespeedoflight.com/article/xcode_4_code_snippets">this post</a> and fell in love with the idea of using XCode 4 snippets.  Up until I read the post, I had heard they existed, but never really tried them.  After reading the post, I began using his snippets as well as started creating my own.  Now, I would say that my work-flow is faster than ever.  
Here is a quick demonstration of the power of snippets
Type:

ttt

It generates:

#pragma mark - UITableView  ...]]></description>
				<content:encoded><![CDATA[<p>Recently, I came across <a href="http://nearthespeedoflight.com/article/xcode_4_code_snippets">this post</a> and fell in love with the idea of using XCode 4 snippets.  Up until I read the post, I had heard they existed, but never really tried them.  After reading the post, I began using his snippets as well as started creating my own.  Now, I would say that my work-flow is faster than ever.  </p>
<p>Here is a quick demonstration of the power of snippets</p>
<p><b>Type:</b></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="bash" style="font-family:monospace;">ttt</pre></td></tr></table></div>

<p><b>It generates:</b></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#pragma mark - UITableView Datasource</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>numberOfSectionsInTableView<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITableView <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>tableView <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">return</span> <span style="color: #2400d9;">1</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>tableView<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITableView <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>tableView numberOfRowsInSection<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>section <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">return</span> <span style="color: #2400d9;">10</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>UITableViewCell <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>tableView<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITableView <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>tableView cellForRowAtIndexPath<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSIndexPath</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>indexPath <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">static</span> <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>cellIdentifier <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cell&quot;</span>;
&nbsp;
    UITableViewCell <span style="color: #002200;">*</span>cell <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>tableView dequeueReusableCellWithIdentifier<span style="color: #002200;">:</span>cellIdentifier<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span>cell <span style="color: #002200;">==</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        cell <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UITableViewCell alloc<span style="color: #002200;">&#93;</span> initWithStyle<span style="color: #002200;">:</span>UITableViewCellStyleDefault reuseIdentifier<span style="color: #002200;">:</span>cellIdentifier<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    cell.textLabel.text <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cell %d&quot;</span>, indexPath.row<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">return</span> cell;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#pragma mark - UITableView Delegate methods</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>tableView<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITableView <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>tableView didSelectRowAtIndexPath<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSIndexPath</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>indexPath <span style="color: #002200;">&#123;</span>
&nbsp;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>As you can see, with 3 keystrokes, I now have a fully working table view implementation with sample data.</p>
<p>This article will be another introduction to XCode 4 snippets but focusing on how to set them up as well as share them with your team.</p>
<h4>Adding A Snippet Inside Of XCode</h4>
<p>In my opinion, this is not very obvious.  The snippet library is fairly well hidden.  To bring it up, first ensure that the right side bar is visible in XCode by selecting the right most option of the &#8220;view&#8221; pane in the top right corner of XCode.</p>
<p><a href="/wp-content/uploads/2011/12/Screen-Shot-2011-12-06-at-3.16.01-PM.png"><img src="/wp-content/uploads/2011/12/Screen-Shot-2011-12-06-at-3.16.01-PM.png" alt="" title="Screen Shot 2011-12-06 at 3.16.01 PM" width="95" height="41" class="alignnone size-full wp-image-3661" /></a></p>
<div style="clear:both">&nbsp;</div>
<p>Now that the right bar is available, click on the &#8220;{}&#8221; option of the bottom most pane.  This will bring up the snippet library.  </p>
<p><a href="/wp-content/uploads/2011/12/Screen-Shot-2011-12-06-at-3.17.10-PM.png"><img src="/wp-content/uploads/2011/12/Screen-Shot-2011-12-06-at-3.17.10-PM.png" alt="" title="Screen Shot 2011-12-06 at 3.17.10 PM" width="260" height="273" class="alignnone size-full wp-image-3662" /></a></p>
<div style="clear:both">&nbsp;</div>
<p>Feel free to browse the snippets that XCode ships with, however most of them are not very useful.  So, now this is where I feel Apple engineers were a little <em>too</em> clever.  It took me a little while to figure out how to actually add a new snippet.  You would expect some sort of + button or something.  The way you add a new snippet in this case is to write out a chunk of code and drag it into the Code Snippet Library window.</p>
<p>Once you drag the code into the library, it creates a default snippet called &#8220;My Code Snippet&#8221;.  Which again, is just terribly non-obvious.  Now, double click on &#8220;My Code Snippet&#8221;, and then click the &#8220;edit&#8221; button to modify it.</p>
<p><a href="/wp-content/uploads/2011/12/Screen-Shot-2011-12-06-at-3.23.42-PM.png"><img src="/wp-content/uploads/2011/12/Screen-Shot-2011-12-06-at-3.23.42-PM.png" alt="" title="Screen Shot 2011-12-06 at 3.23.42 PM" width="447" height="298" class="alignnone size-full wp-image-3663" /></a></p>
<div style="clear:both">&nbsp;</div>
<p>Let&#8217;s talk about each of the important fields:</p>
<ol>
<li>Title &#8211; This is just the common name you will use to refer to the snippet.  It will display during autocompletion</li>
<li>Completion Shortcut &#8211; this is the command you will use to invoke the snippet.  For example, I have ttt to automatically create all of the UITableView delegate and datasource methods with sample data.</li>
<li>Completion Scopes &#8211; This is pretty cool.  You can have the same shortcut to represent differnet snippets based on the scope of the document.  For example, you won&#8217;t want to invoke your @property snippets inside of your Class implementation.  So, they get ignored&#8230;</li>
</ol>
<p><strong>Adding dynamic fields</strong></p>
<p>If you notice, many of Apple&#8217;s auto generated classes or snippets (like UIAlertView), have these &#8220;code bubbles&#8221; hinting at the type of data you should put into them.  They are also nice because they allow you to tab between them enabling you to implement the code quicker.  To add your own simply insert this into your code:</p>
<p><strong>&lt;#Text#></strong></p>
<p>Where &#8220;Text&#8221; is whatever you want the code bubble to say.  </p>
<p>That&#8217;s it, when you are finished click done and you should now be able to use your snippets.</p>
<h4>Sharing Snippets</h4>
<p>While XCode doesn&#8217;t have an export button for snippets, they are in a fairly predictable location.  They are located at:</p>
<p><strong>~/Library/Developer/Xcode/UserData/CodeSnippets/</strong></p>
<p>That being said, you could manually share them between developers (zip them up and email) OR you could version control this folder with something like git.  I really like the latter approach.  Any time a developer adds a new snippet to the library, the others just have to pull, restart XCode, and voila the snippet is there.</p>
<h4>Conclusion</h4>
<p>The only issue now is remembering to actually use your snippets in practice.  It takes some getting used to, but I&#8217;m sure you will get it.  Below, you can download a zip file containing many of the snippets that I use.  Simply unzip it into the folder that I mentioned above.  </p>
<p><a href='/wp-content/uploads/2011/12/XCode-4-snippets.zip'>Download My Snippets</a></p>
<p>Happy iCoding!</p>
<p><a href="http://twitter.com/brandontreb">Follow me on Twitter</a></p>
<!-- Start Sociable --><div class="sociable"><ul class='clearfix'></ul><div onMouseout="fixOnMouseOut(this,event,'post-3658')" id="sociable-post-3658" style="display:none;">   

    <div style="top: auto; left: auto; display: block;" id="sociable">



		<div class="popup">

			<div class="content">

				<ul><li style="heigth:32px;width:32px"><a title="Facebook" class="option1_32" style="background-position:-96px 0px" rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;t=Using%20XCode%204%20Snippets%20"></a></li><li style="heigth:32px;width:32px"><a title="Myspace" class="option1_32" style="background-position:0px -32px" rel="nofollow" target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;t=Using%20XCode%204%20Snippets%20"></a></li><li style="heigth:32px;width:32px"><a title="Twitter" class="option1_32" style="background-position:-288px -32px" rel="nofollow" target="_blank" href="http://twitter.com/intent/tweet?text=Using%20XCode%204%20Snippets%20%20-%20http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F%20  SHARETAG"></a></li><li style="heigth:32px;width:32px"><a title="LinkedIn" class="option1_32" style="background-position:-288px 0px" rel="nofollow" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;title=Using%20XCode%204%20Snippets%20&amp;source=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials&amp;summary=Recently%2C%20I%20came%20across%20this%20post%20and%20fell%20in%20love%20with%20the%20idea%20of%20using%20XCode%204%20snippets.%20%20Up%20until%20I%20read%20the%20post%2C%20I%20had%20heard%20they%20existed%2C%20but%20never%20really%20tried%20them.%20%20After%20reading%20the%20post%2C%20I%20began%20using%20his%20snippets%20as%20well%20as%20started%20creat"></a></li><li style="heigth:32px;width:32px"><a title="Delicious" class="option1_32" style="background-position:-32px 0px" rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;title=Using%20XCode%204%20Snippets%20&amp;notes=Recently%2C%20I%20came%20across%20this%20post%20and%20fell%20in%20love%20with%20the%20idea%20of%20using%20XCode%204%20snippets.%20%20Up%20until%20I%20read%20the%20post%2C%20I%20had%20heard%20they%20existed%2C%20but%20never%20really%20tried%20them.%20%20After%20reading%20the%20post%2C%20I%20began%20using%20his%20snippets%20as%20well%20as%20started%20creat"></a></li><li style="heigth:32px;width:32px"><a title="Digg" class="option1_32" style="background-position:-64px 0px" rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;title=Using%20XCode%204%20Snippets%20&amp;bodytext=Recently%2C%20I%20came%20across%20this%20post%20and%20fell%20in%20love%20with%20the%20idea%20of%20using%20XCode%204%20snippets.%20%20Up%20until%20I%20read%20the%20post%2C%20I%20had%20heard%20they%20existed%2C%20but%20never%20really%20tried%20them.%20%20After%20reading%20the%20post%2C%20I%20began%20using%20his%20snippets%20as%20well%20as%20started%20creat"></a></li><li style="heigth:32px;width:32px"><a title="Reddit" class="option1_32" style="background-position:-128px -32px" rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;title=Using%20XCode%204%20Snippets%20"></a></li><li style="heigth:32px;width:32px"><a title="StumbleUpon" class="option1_32" style="background-position:-224px -32px" rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&title=Using%20XCode%204%20Snippets%20"></a></li><li style="heigth:32px;width:32px"><a title="Google Bookmarks" class="option1_32" style="background-position:-192px 0px" rel="nofollow" target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;title=Using%20XCode%204%20Snippets%20&amp;annotation=Recently%2C%20I%20came%20across%20this%20post%20and%20fell%20in%20love%20with%20the%20idea%20of%20using%20XCode%204%20snippets.%20%20Up%20until%20I%20read%20the%20post%2C%20I%20had%20heard%20they%20existed%2C%20but%20never%20really%20tried%20them.%20%20After%20reading%20the%20post%2C%20I%20began%20using%20his%20snippets%20as%20well%20as%20started%20creat"></a></li><li style="heigth:32px;width:32px"><a title="HackerNews" class="option1_32" style="background-position:-256px 0px" rel="nofollow" target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;t=Using%20XCode%204%20Snippets%20"></a></li><li style="heigth:32px;width:32px"><a title="MSNReporter" class="option1_32" style="background-position:-352px 0px" rel="nofollow" target="_blank" href="http://reporter.es.msn.com/?fn=contribute&amp;Title=Using%20XCode%204%20Snippets%20&amp;URL=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;cat_id=6&amp;tag_id=31&amp;Remark=Recently%2C%20I%20came%20across%20this%20post%20and%20fell%20in%20love%20with%20the%20idea%20of%20using%20XCode%204%20snippets.%20%20Up%20until%20I%20read%20the%20post%2C%20I%20had%20heard%20they%20existed%2C%20but%20never%20really%20tried%20them.%20%20After%20reading%20the%20post%2C%20I%20began%20using%20his%20snippets%20as%20well%20as%20started%20creat"></a></li><li style="heigth:32px;width:32px"><a title="BlinkList" class="option1_32" style="background-position:0px 0px" rel="nofollow" target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;Title=Using%20XCode%204%20Snippets%20"></a></li><li style="heigth:32px;width:32px"><a title="Sphinn" class="option1_32" style="background-position:-192px -32px" rel="nofollow" target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F"></a></li><li style="heigth:32px;width:32px"><a title="Posterous" class="option1_32" style="background-position:-64px -32px" rel="nofollow" target="_blank" href="http://posterous.com/share?linkto=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;title=Using%20XCode%204%20Snippets%20&amp;selection=Recently%2C%20I%20came%20across%20this%20post%20and%20fell%20in%20love%20with%20the%20idea%20of%20using%20XCode%204%20snippets.%20%20Up%20until%20I%20read%20the%20post%2C%20I%20had%20heard%20they%20existed%2C%20but%20never%20really%20tried%20them.%20%20After%20reading%20the%20post%2C%20I%20began%20using%20his%20snippets%20as%20well%20as%20started%20creat"></a></li><li style="heigth:32px;width:32px"><a title="Tumblr" class="option1_32" style="background-position:-256px -32px" rel="nofollow" target="_blank" href="http://www.tumblr.com/share?v=3&amp;u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;t=Using%20XCode%204%20Snippets%20&amp;s=Recently%2C%20I%20came%20across%20this%20post%20and%20fell%20in%20love%20with%20the%20idea%20of%20using%20XCode%204%20snippets.%20%20Up%20until%20I%20read%20the%20post%2C%20I%20had%20heard%20they%20existed%2C%20but%20never%20really%20tried%20them.%20%20After%20reading%20the%20post%2C%20I%20began%20using%20his%20snippets%20as%20well%20as%20started%20creat"></a></li><li style="heigth:32px;width:32px"><a title="email" class="option1_32" style="background-position:-160px 0px" rel="nofollow" target="_blank" href="https://mail.google.com/mail/?view=cm&fs=1&to&su=Using%20XCode%204%20Snippets%20&body=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&ui=2&tf=1&shva=1"></a></li><li style="heigth:32px;width:32px"><a title="Google Reader" class="option1_32" style="background-position:-224px 0px" rel="nofollow" target="_blank" href="http://www.google.com/reader/link?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;title=Using%20XCode%204%20Snippets%20&amp;srcURL=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F12%2F06%2Fusing-xcode-4-snippets%2F&amp;srcTitle=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials"></a></li><li style="heigth:32px;width:32px"><a class="option1_32" style="cursor:pointer;background-position:-128px 0px" rel="nofollow" title="Add to favorites - doesn't work in Chrome"  onClick="javascript:AddToFavorites();"></a></li><li style="heigth:32px;width:32px"><a style="cursor:poainter" rel="nofollow"   onMouseOver="more(this,'post-3658')"><img style='margin-top:9px' src='/wp-content/plugins/sociable/images/more.png'></a></li></ul>			

			</div>        

		  <a style="cursor:pointer" onclick="hide_sociable('post-3658',true)" class="close">

		  <img onclick="hide_sociable('post-3658',true)" title="close" src="/wp-content/plugins/sociable/images/closelabel.png">

		  </a>

		</div>

	</div> 

  </div></div><div class='sociable' style='float:none'><ul class='clearfix'><li id="Twitter_Counter"><a href="https://twitter.com/share" data-text="Using XCode 4 Snippets  - http://icodeblog.com/2011/12/06/using-xcode-4-snippets/" data-url="http://icodeblog.com/2011/12/06/using-xcode-4-snippets/" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></li><li id="Facebook_Counter"><iframe src="http://www.facebook.com/plugins/like.php?href=http://icodeblog.com/2011/12/06/using-xcode-4-snippets/&send=false&layout=button_count&show_faces=false&action=like&colorscheme=light&font" scrolling="no" frameborder="0" style="border:none; overflow:hidden;height:32px;width:100px" allowTransparency="true"></iframe></li><li id="Google_p"><g:plusone annotation="bubble" href="/2011/12/06/using-xcode-4-snippets/" size="medium"></g:plusone></li><li id="LinkedIn_Counter"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="http://icodeblog.com/2011/12/06/using-xcode-4-snippets/" data-counter="right"></script></li></ul></div><!-- End Sociable -->]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2011/12/06/using-xcode-4-snippets/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Making UITableViews look not so plain</title>
		<link>http://icodeblog.com/2011/11/19/making-uitableviews-look-not-so-plain/</link>
		<comments>http://icodeblog.com/2011/11/19/making-uitableviews-look-not-so-plain/#comments</comments>
		<pubDate>Sat, 19 Nov 2011 00:57:33 +0000</pubDate>
		<dc:creator><![CDATA[James Van Metre]]></dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[beginner]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=3622</guid>
		<description><![CDATA[As most of you probably know, UITableView&#8217;s are incredibly useful and versatile views to be using in your applications.
If you have ever tried to customize a UITableView though, you know that as soon as you start adding lots of UIViews, UILabels, and UImageViews to a cells ContentView, that these tableviews start to scroll slower and slower, and become choppier and choppier.
What we are going to explore today is how to remedy that situation.
To download the entire XCode project, you can  ...]]></description>
				<content:encoded><![CDATA[<p>As most of you probably know, UITableView&#8217;s are incredibly useful and versatile views to be using in your applications.<br />
If you have ever tried to customize a UITableView though, you know that as soon as you start adding lots of UIViews, UILabels, and UImageViews to a cells ContentView, that these tableviews start to scroll slower and slower, and become choppier and choppier.</p>
<p>What we are going to explore today is how to remedy that situation.<br />
To download the entire XCode project, you can find it at:  <a href="http://github.com/elc/ICB_PrettyTableView">http://github.com/elc/ICB_PrettyTableView</a></p>
<p>We are going to build a simple contact viewer, that will display the phones contacts. For each contact, if they have a first name, last name, email and phone number, they will be displayed within one cell, with different colors. The reason this is useful is because it provides the basics for customizing UITableViewCells that can really start to make your application look nice, and still scroll well.<br />
If you don&#8217;t want to have simulated data inside the simulator, check out this post for copying data from your device to the simulator: <a href="/2011/11/09/how-to-import-contacts-into-the-iphone-simulator/">How to import contacts into the iphone simulator</a></p>
<p>In this example, we have a standard UITableViewController. We are going to have a couple class variables defined in the header</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &lt;UIKit/UIKit.h&gt;</span>
<span style="color: #6e371a;">#import &lt;AddressBook/AddressBook.h&gt;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> ICBTableViewController <span style="color: #002200;">:</span> UITableViewController
<span style="color: #002200;">&#123;</span>
    ABAddressBookRef _addressBook;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>contacts;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p> ABAddressBookRef _addressBook is defined in our header, so that we don&#8217;t have to release it until we dealloc. And the contacts is so that we can hold on to the data for our tableView.<br />
In the main table view controller file we are going to override the &#8211; (void)viewDidLoad to provide some initial configuration of the tableView, as well as loading or generating our data. (We will generate fake data for devices or the simulator that don&#8217;t have address book data)</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewDidLoad
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super viewDidLoad<span style="color: #002200;">&#93;</span>;
    self.tableView.backgroundColor <span style="color: #002200;">=</span> UIColor.blackColor;
    self.tableView.separatorStyle <span style="color: #002200;">=</span> UITableViewCellSeparatorStyleNone;
&nbsp;
    ABAddressBookRef addressBook <span style="color: #002200;">=</span> ABAddressBookCreate<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>tempArray <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>ABAddressBookCopyArrayOfAllPeople<span style="color: #002200;">&#40;</span>addressBook<span style="color: #002200;">&#41;</span>;
    tempArray <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>tempArray sortedArrayUsingComparator<span style="color: #002200;">:^</span>NSComparisonResult<span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span> obj1, <span style="color: #a61390;">id</span> obj2<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>name1 <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>ABRecordCopyCompositeName<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>ABRecordRef<span style="color: #002200;">&#41;</span>obj1<span style="color: #002200;">&#41;</span>;
        <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>name2 <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>ABRecordCopyCompositeName<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>ABRecordRef<span style="color: #002200;">&#41;</span>obj2<span style="color: #002200;">&#41;</span>;
        <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>name1 compare<span style="color: #002200;">:</span>name2<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>tempArray count<span style="color: #002200;">&#93;</span> &gt; <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        self.contacts <span style="color: #002200;">=</span> tempArray;
    <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #400080;">NSMutableArray</span> <span style="color: #002200;">*</span>tempMutableArray <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableArray</span> arrayWithCapacity<span style="color: #002200;">:</span><span style="color: #2400d9;">100</span><span style="color: #002200;">&#93;</span>;
        <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> i <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>; i &lt; <span style="color: #2400d9;">100</span>; <span style="color: #002200;">++</span>i<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            <span style="color: #400080;">NSMutableDictionary</span> <span style="color: #002200;">*</span>dict <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableDictionary</span> dictionary<span style="color: #002200;">&#93;</span>;
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>i <span style="color: #002200;">%</span> <span style="color: #2400d9;">9</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">!=</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                <span style="color: #002200;">&#91;</span>dict setObject<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;FirstName%d&quot;</span>, i<span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;firstName&quot;</span><span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span>
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>i <span style="color: #002200;">%</span> <span style="color: #2400d9;">3</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">==</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                <span style="color: #002200;">&#91;</span>dict setObject<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;LastName%d&quot;</span>, i<span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;lastName&quot;</span><span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span>
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>i <span style="color: #002200;">%</span> <span style="color: #2400d9;">3</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">==</span> <span style="color: #2400d9;">0</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#40;</span>i <span style="color: #002200;">%</span> <span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">==</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                <span style="color: #002200;">&#91;</span>dict setObject<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;emailTest%d@test%d.com&quot;</span>, i, i<span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;email&quot;</span><span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span>
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>i <span style="color: #002200;">%</span> <span style="color: #2400d9;">7</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">==</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #a61390;">string</span> <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%d&quot;</span>, i<span style="color: #002200;">&#93;</span>;
                <span style="color: #a61390;">while</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #a61390;">string</span> length<span style="color: #002200;">&#93;</span> &lt; <span style="color: #2400d9;">10</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                    <span style="color: #a61390;">string</span> <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #a61390;">string</span> stringByAppendingFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, <span style="color: #a61390;">string</span><span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#125;</span>
                <span style="color: #002200;">&#91;</span>dict setObject<span style="color: #002200;">:</span><span style="color: #a61390;">string</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;phone&quot;</span><span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span>
            <span style="color: #002200;">&#91;</span>tempMutableArray addObject<span style="color: #002200;">:</span>dict<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span>
        self.contacts <span style="color: #002200;">=</span> tempMutableArray;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>As you can see here we have a couple of self.tableView methods we have called to setup the background color, and also the cell separator style.<br />
If you are running this application on a device, or simulator that has contacts, this method will also make a copy of the address book as the data to display. If there is no data in the address book, we create some fake test data just for displaying.<br />
Also don&#8217;t forget to include our &#8211; (void)dealloc method for releasing our _addressBook variable.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>dealloc
<span style="color: #002200;">&#123;</span>
    CFRelease<span style="color: #002200;">&#40;</span>_addressBook<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#91;</span>_contacts release<span style="color: #002200;">&#93;</span>;
    _contacts <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>We have to supply the tableView with our number of rows</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>tableView<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITableView <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>tableView numberOfRowsInSection<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>section
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>self.contacts count<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>The next portion we have to override is the &#8211; (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath so that we can supply the tableView with our cells.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Customize the appearance of table view cells.</span>
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>UITableViewCell <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>tableView<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITableView <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>tableView cellForRowAtIndexPath<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSIndexPath</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>indexPath
<span style="color: #002200;">&#123;</span>   
&nbsp;
    <span style="color: #a61390;">static</span> <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>CellIdentifier <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;ICBTableViewCellIdentifier&quot;</span>;
&nbsp;
    ICBTableViewCell <span style="color: #002200;">*</span>cell <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>ICBTableViewCell<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>tableView dequeueReusableCellWithIdentifier<span style="color: #002200;">:</span>CellIdentifier<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>cell <span style="color: #002200;">==</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        cell <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>ICBTableViewCell alloc<span style="color: #002200;">&#93;</span> initWithStyle<span style="color: #002200;">:</span>UITableViewCellStyleDefault reuseIdentifier<span style="color: #002200;">:</span>CellIdentifier<span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
        cell.textLabel.textColor <span style="color: #002200;">=</span> UIColor.whiteColor;
    <span style="color: #002200;">&#125;</span>
    cell.tag <span style="color: #002200;">=</span> indexPath.row;
&nbsp;
    <span style="color: #400080;">NSObject</span> <span style="color: #002200;">*</span>object <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self.contacts objectAtIndex<span style="color: #002200;">:</span>indexPath.row<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>object isKindOfClass<span style="color: #002200;">:</span><span style="color: #400080;">NSDictionary</span>.class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>cell setDictionary<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>object<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>cell setRecord<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>ABRecordRef<span style="color: #002200;">&#41;</span>object<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #a61390;">return</span> cell;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>We are checking each object coming out of our array so that we can determine if we need to call the setDictionary, or setRecord method calls.</p>
<p>Now the meat of this tutorial, extending a UITableViewCell.</p>
<p>In our header we are going to define a bunch of strings that we want to display</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &lt;UIKit/UIKit.h&gt;</span>
<span style="color: #6e371a;">#import &lt;AddressBook/AddressBook.h&gt;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> ICBTableViewCell <span style="color: #002200;">:</span> UITableViewCell
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>firstName;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>lastName;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>email;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>phone;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>address;
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setRecord<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>ABRecordRef<span style="color: #002200;">&#41;</span>record;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setDictionary<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>dict;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>And then our two set methods:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setRecord<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>ABRecordRef<span style="color: #002200;">&#41;</span>record
<span style="color: #002200;">&#123;</span>
    self.firstName <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>ABRecordCopyValue<span style="color: #002200;">&#40;</span>record, kABPersonFirstNameProperty<span style="color: #002200;">&#41;</span> autorelease<span style="color: #002200;">&#93;</span>;
    self.lastName <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>ABRecordCopyValue<span style="color: #002200;">&#40;</span>record, kABPersonLastNameProperty<span style="color: #002200;">&#41;</span> autorelease<span style="color: #002200;">&#93;</span>;
    self.email <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self getFirstEmail<span style="color: #002200;">:</span>record<span style="color: #002200;">&#93;</span>;
    self.phone <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self getFirstPhone<span style="color: #002200;">:</span>record<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>self setNeedsDisplay<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setDictionary<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>dict
<span style="color: #002200;">&#123;</span>
    self.firstName <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>dict objectForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;firstName&quot;</span><span style="color: #002200;">&#93;</span>;
    self.lastName <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>dict objectForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;lastName&quot;</span><span style="color: #002200;">&#93;</span>;
    self.email <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>dict objectForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;email&quot;</span><span style="color: #002200;">&#93;</span>;
    self.phone <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>dict objectForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;phone&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>self setNeedsDisplay<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Some tutorials will have you put this next part into a separate UIView subclass, and add that class as the contentView of this UITableViewCell, but I prefer to override the drawRect of the UITableViewCell, and do all my drawing there.</p>
<p>The first thing I am doing is getting the current graphics context so that we can draw to the screen, clipping to the rect that is passed in drawRect:(CGRect)rect, and then depending on whether this cell is even, I am filling the entire rect with an almost black color, or slightly lighter.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>drawRect<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGRect<span style="color: #002200;">&#41;</span>rect
<span style="color: #002200;">&#123;</span>
    CGContextRef ctx <span style="color: #002200;">=</span> UIGraphicsGetCurrentContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
    CGContextClipToRect<span style="color: #002200;">&#40;</span>ctx, rect<span style="color: #002200;">&#41;</span>;
    <span style="color: #11740a; font-style: italic;">//If even</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>self.tag <span style="color: #002200;">%</span> <span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">==</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        CGContextSetFillColorWithColor<span style="color: #002200;">&#40;</span>ctx, <span style="color: #002200;">&#91;</span>UIColor colorWithWhite<span style="color: #002200;">:</span>0.1f alpha<span style="color: #002200;">:</span><span style="color: #2400d9;">1</span>.f<span style="color: #002200;">&#93;</span>.CGColor<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
        CGContextSetFillColorWithColor<span style="color: #002200;">&#40;</span>ctx, <span style="color: #002200;">&#91;</span>UIColor colorWithWhite<span style="color: #002200;">:</span>0.15f alpha<span style="color: #002200;">:</span><span style="color: #2400d9;">1</span>.f<span style="color: #002200;">&#93;</span>.CGColor<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    CGContextFillRect<span style="color: #002200;">&#40;</span>ctx, rect<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>The next thing I am going to figure out is whether I want this text to be centered in the cell, and I am determining this based off whether there is an email field or not.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">    <span style="color: #11740a; font-style: italic;">//Vertically center our text, if no email</span>
    <span style="color: #a61390;">BOOL</span> isCentered <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>self.email <span style="color: #002200;">==</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>And now for the meat of the drawRect method. We calculate the size of firstName, draw it offset from the left by 5, and then draw lastName right after it. We also change the color we are drawing between those two. </p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">    CGRect tempRect;
    CGFloat midY <span style="color: #002200;">=</span> CGRectGetMidY<span style="color: #002200;">&#40;</span>rect<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIColor whiteColor<span style="color: #002200;">&#93;</span> set<span style="color: #002200;">&#93;</span>;
    UIFont <span style="color: #002200;">*</span>defaultFont <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIFont systemFontOfSize<span style="color: #002200;">:</span><span style="color: #2400d9;">16</span><span style="color: #002200;">&#93;</span>;
    CGSize size <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self.firstName sizeWithFont<span style="color: #002200;">:</span>defaultFont<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>isCentered <span style="color: #002200;">==</span> <span style="color: #a61390;">NO</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        tempRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">5</span>, <span style="color: #2400d9;">0</span>, size.width, size.height<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
        tempRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">5</span>, midY <span style="color: #002200;">-</span> size.height<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span>, size.width, size.height<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#91;</span>self.firstName drawInRect<span style="color: #002200;">:</span>tempRect withFont<span style="color: #002200;">:</span>defaultFont<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIColor lightGrayColor<span style="color: #002200;">&#93;</span> set<span style="color: #002200;">&#93;</span>;
    size <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self.lastName sizeWithFont<span style="color: #002200;">:</span>defaultFont<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>isCentered <span style="color: #002200;">==</span> <span style="color: #a61390;">NO</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        tempRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span>CGRectGetMaxX<span style="color: #002200;">&#40;</span>tempRect<span style="color: #002200;">&#41;</span><span style="color: #002200;">+</span><span style="color: #2400d9;">5</span>, <span style="color: #2400d9;">0</span>, size.width, size.height<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
        tempRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span>CGRectGetMaxX<span style="color: #002200;">&#40;</span>tempRect<span style="color: #002200;">&#41;</span><span style="color: #002200;">+</span><span style="color: #2400d9;">5</span>, midY <span style="color: #002200;">-</span> size.height<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span>, size.width, size.height<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#91;</span>self.lastName drawInRect<span style="color: #002200;">:</span>tempRect withFont<span style="color: #002200;">:</span>defaultFont<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>Next we find out if phone actually exists, and if so set the color to red, and draw it to the right of lastName. We also have to make sure we aren&#8217;t drawing this outside our boundaries, so we check to see where the end is, and if it is outside, we crop it to 5 pixels from the end.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>self.phone <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIColor redColor<span style="color: #002200;">&#93;</span> set<span style="color: #002200;">&#93;</span>;
        size <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self.phone sizeWithFont<span style="color: #002200;">:</span>defaultFont<span style="color: #002200;">&#93;</span>;
        CGFloat end <span style="color: #002200;">=</span> CGRectGetMaxX<span style="color: #002200;">&#40;</span>tempRect<span style="color: #002200;">&#41;</span> <span style="color: #002200;">+</span> size.width;
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>end &gt; rect.size.width<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            size.width <span style="color: #002200;">=</span> CGRectGetMaxX<span style="color: #002200;">&#40;</span>rect<span style="color: #002200;">&#41;</span> <span style="color: #002200;">-</span> CGRectGetMaxX<span style="color: #002200;">&#40;</span>tempRect<span style="color: #002200;">&#41;</span> <span style="color: #002200;">-</span> <span style="color: #2400d9;">10</span>; <span style="color: #11740a; font-style: italic;">//-10 so that we get 5 from the end of last name, and 5 from the end of rect</span>
        <span style="color: #002200;">&#125;</span>
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>isCentered <span style="color: #002200;">==</span> <span style="color: #a61390;">NO</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            tempRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span>CGRectGetMaxX<span style="color: #002200;">&#40;</span>rect<span style="color: #002200;">&#41;</span> <span style="color: #002200;">-</span> size.width <span style="color: #002200;">-</span> <span style="color: #2400d9;">5</span>, <span style="color: #2400d9;">0</span>, size.width, size.height<span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
            tempRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span>CGRectGetMaxX<span style="color: #002200;">&#40;</span>rect<span style="color: #002200;">&#41;</span> <span style="color: #002200;">-</span> size.width <span style="color: #002200;">-</span> <span style="color: #2400d9;">5</span>, midY <span style="color: #002200;">-</span> size.height<span style="color: #002200;">/</span><span style="color: #2400d9;">2</span>, size.width, size.height<span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#125;</span>
        <span style="color: #002200;">&#91;</span>self.phone drawInRect<span style="color: #002200;">:</span>tempRect withFont<span style="color: #002200;">:</span>defaultFont lineBreakMode<span style="color: #002200;">:</span>UILineBreakModeTailTruncation<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>And finally if our email actually exists draw it on the bottom left.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>self.email <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIColor blueColor<span style="color: #002200;">&#93;</span> set<span style="color: #002200;">&#93;</span>;
        size <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self.email sizeWithFont<span style="color: #002200;">:</span>defaultFont<span style="color: #002200;">&#93;</span>;
        tempRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">5</span>, midY, size.width, size.height<span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#91;</span>self.email drawInRect<span style="color: #002200;">:</span>tempRect withFont<span style="color: #002200;">:</span>defaultFont<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>I hope this helps you in configuring UITableViewCells for your own project, and hopefully will let you start to think about the possibilities.</p>
<p>To download the entire XCode project, you can find it at:  <a href="http://github.com/elc/ICB_PrettyTableView">http://github.com/elc/ICB_PrettyTableView</a></p>
<!-- Start Sociable --><div class="sociable"><ul class='clearfix'></ul><div onMouseout="fixOnMouseOut(this,event,'post-3622')" id="sociable-post-3622" style="display:none;">   

    <div style="top: auto; left: auto; display: block;" id="sociable">



		<div class="popup">

			<div class="content">

				<ul><li style="heigth:32px;width:32px"><a title="Facebook" class="option1_32" style="background-position:-96px 0px" rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;t=Making%20UITableViews%20look%20not%20so%20plain"></a></li><li style="heigth:32px;width:32px"><a title="Myspace" class="option1_32" style="background-position:0px -32px" rel="nofollow" target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;t=Making%20UITableViews%20look%20not%20so%20plain"></a></li><li style="heigth:32px;width:32px"><a title="Twitter" class="option1_32" style="background-position:-288px -32px" rel="nofollow" target="_blank" href="http://twitter.com/intent/tweet?text=Making%20UITableViews%20look%20not%20so%20plain%20-%20http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F%20  SHARETAG"></a></li><li style="heigth:32px;width:32px"><a title="LinkedIn" class="option1_32" style="background-position:-288px 0px" rel="nofollow" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;title=Making%20UITableViews%20look%20not%20so%20plain&amp;source=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials&amp;summary=As%20most%20of%20you%20probably%20know%2C%20UITableView%27s%20are%20incredibly%20useful%20and%20versatile%20views%20to%20be%20using%20in%20your%20applications.%0D%0AIf%20you%20have%20ever%20tried%20to%20customize%20a%20UITableView%20though%2C%20you%20know%20that%20as%20soon%20as%20you%20start%20adding%20lots%20of%20UIViews%2C%20UILabels%2C%20an"></a></li><li style="heigth:32px;width:32px"><a title="Delicious" class="option1_32" style="background-position:-32px 0px" rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;title=Making%20UITableViews%20look%20not%20so%20plain&amp;notes=As%20most%20of%20you%20probably%20know%2C%20UITableView%27s%20are%20incredibly%20useful%20and%20versatile%20views%20to%20be%20using%20in%20your%20applications.%0D%0AIf%20you%20have%20ever%20tried%20to%20customize%20a%20UITableView%20though%2C%20you%20know%20that%20as%20soon%20as%20you%20start%20adding%20lots%20of%20UIViews%2C%20UILabels%2C%20an"></a></li><li style="heigth:32px;width:32px"><a title="Digg" class="option1_32" style="background-position:-64px 0px" rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;title=Making%20UITableViews%20look%20not%20so%20plain&amp;bodytext=As%20most%20of%20you%20probably%20know%2C%20UITableView%27s%20are%20incredibly%20useful%20and%20versatile%20views%20to%20be%20using%20in%20your%20applications.%0D%0AIf%20you%20have%20ever%20tried%20to%20customize%20a%20UITableView%20though%2C%20you%20know%20that%20as%20soon%20as%20you%20start%20adding%20lots%20of%20UIViews%2C%20UILabels%2C%20an"></a></li><li style="heigth:32px;width:32px"><a title="Reddit" class="option1_32" style="background-position:-128px -32px" rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;title=Making%20UITableViews%20look%20not%20so%20plain"></a></li><li style="heigth:32px;width:32px"><a title="StumbleUpon" class="option1_32" style="background-position:-224px -32px" rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&title=Making%20UITableViews%20look%20not%20so%20plain"></a></li><li style="heigth:32px;width:32px"><a title="Google Bookmarks" class="option1_32" style="background-position:-192px 0px" rel="nofollow" target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;title=Making%20UITableViews%20look%20not%20so%20plain&amp;annotation=As%20most%20of%20you%20probably%20know%2C%20UITableView%27s%20are%20incredibly%20useful%20and%20versatile%20views%20to%20be%20using%20in%20your%20applications.%0D%0AIf%20you%20have%20ever%20tried%20to%20customize%20a%20UITableView%20though%2C%20you%20know%20that%20as%20soon%20as%20you%20start%20adding%20lots%20of%20UIViews%2C%20UILabels%2C%20an"></a></li><li style="heigth:32px;width:32px"><a title="HackerNews" class="option1_32" style="background-position:-256px 0px" rel="nofollow" target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;t=Making%20UITableViews%20look%20not%20so%20plain"></a></li><li style="heigth:32px;width:32px"><a title="MSNReporter" class="option1_32" style="background-position:-352px 0px" rel="nofollow" target="_blank" href="http://reporter.es.msn.com/?fn=contribute&amp;Title=Making%20UITableViews%20look%20not%20so%20plain&amp;URL=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;cat_id=6&amp;tag_id=31&amp;Remark=As%20most%20of%20you%20probably%20know%2C%20UITableView%27s%20are%20incredibly%20useful%20and%20versatile%20views%20to%20be%20using%20in%20your%20applications.%0D%0AIf%20you%20have%20ever%20tried%20to%20customize%20a%20UITableView%20though%2C%20you%20know%20that%20as%20soon%20as%20you%20start%20adding%20lots%20of%20UIViews%2C%20UILabels%2C%20an"></a></li><li style="heigth:32px;width:32px"><a title="BlinkList" class="option1_32" style="background-position:0px 0px" rel="nofollow" target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;Title=Making%20UITableViews%20look%20not%20so%20plain"></a></li><li style="heigth:32px;width:32px"><a title="Sphinn" class="option1_32" style="background-position:-192px -32px" rel="nofollow" target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F"></a></li><li style="heigth:32px;width:32px"><a title="Posterous" class="option1_32" style="background-position:-64px -32px" rel="nofollow" target="_blank" href="http://posterous.com/share?linkto=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;title=Making%20UITableViews%20look%20not%20so%20plain&amp;selection=As%20most%20of%20you%20probably%20know%2C%20UITableView%27s%20are%20incredibly%20useful%20and%20versatile%20views%20to%20be%20using%20in%20your%20applications.%0D%0AIf%20you%20have%20ever%20tried%20to%20customize%20a%20UITableView%20though%2C%20you%20know%20that%20as%20soon%20as%20you%20start%20adding%20lots%20of%20UIViews%2C%20UILabels%2C%20an"></a></li><li style="heigth:32px;width:32px"><a title="Tumblr" class="option1_32" style="background-position:-256px -32px" rel="nofollow" target="_blank" href="http://www.tumblr.com/share?v=3&amp;u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;t=Making%20UITableViews%20look%20not%20so%20plain&amp;s=As%20most%20of%20you%20probably%20know%2C%20UITableView%27s%20are%20incredibly%20useful%20and%20versatile%20views%20to%20be%20using%20in%20your%20applications.%0D%0AIf%20you%20have%20ever%20tried%20to%20customize%20a%20UITableView%20though%2C%20you%20know%20that%20as%20soon%20as%20you%20start%20adding%20lots%20of%20UIViews%2C%20UILabels%2C%20an"></a></li><li style="heigth:32px;width:32px"><a title="email" class="option1_32" style="background-position:-160px 0px" rel="nofollow" target="_blank" href="https://mail.google.com/mail/?view=cm&fs=1&to&su=Making%20UITableViews%20look%20not%20so%20plain&body=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&ui=2&tf=1&shva=1"></a></li><li style="heigth:32px;width:32px"><a title="Google Reader" class="option1_32" style="background-position:-224px 0px" rel="nofollow" target="_blank" href="http://www.google.com/reader/link?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;title=Making%20UITableViews%20look%20not%20so%20plain&amp;srcURL=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F19%2Fmaking-uitableviews-look-not-so-plain%2F&amp;srcTitle=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials"></a></li><li style="heigth:32px;width:32px"><a class="option1_32" style="cursor:pointer;background-position:-128px 0px" rel="nofollow" title="Add to favorites - doesn't work in Chrome"  onClick="javascript:AddToFavorites();"></a></li><li style="heigth:32px;width:32px"><a style="cursor:poainter" rel="nofollow"   onMouseOver="more(this,'post-3622')"><img style='margin-top:9px' src='/wp-content/plugins/sociable/images/more.png'></a></li></ul>			

			</div>        

		  <a style="cursor:pointer" onclick="hide_sociable('post-3622',true)" class="close">

		  <img onclick="hide_sociable('post-3622',true)" title="close" src="/wp-content/plugins/sociable/images/closelabel.png">

		  </a>

		</div>

	</div> 

  </div></div><div class='sociable' style='float:none'><ul class='clearfix'><li id="Twitter_Counter"><a href="https://twitter.com/share" data-text="Making UITableViews look not so plain - http://icodeblog.com/2011/11/19/making-uitableviews-look-not-so-plain/" data-url="http://icodeblog.com/2011/11/19/making-uitableviews-look-not-so-plain/" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></li><li id="Facebook_Counter"><iframe src="http://www.facebook.com/plugins/like.php?href=http://icodeblog.com/2011/11/19/making-uitableviews-look-not-so-plain/&send=false&layout=button_count&show_faces=false&action=like&colorscheme=light&font" scrolling="no" frameborder="0" style="border:none; overflow:hidden;height:32px;width:100px" allowTransparency="true"></iframe></li><li id="Google_p"><g:plusone annotation="bubble" href="/2011/11/19/making-uitableviews-look-not-so-plain/" size="medium"></g:plusone></li><li id="LinkedIn_Counter"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="http://icodeblog.com/2011/11/19/making-uitableviews-look-not-so-plain/" data-counter="right"></script></li></ul></div><!-- End Sociable -->]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2011/11/19/making-uitableviews-look-not-so-plain/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>How to import contacts into the iPhone Simulator</title>
		<link>http://icodeblog.com/2011/11/09/how-to-import-contacts-into-the-iphone-simulator/</link>
		<comments>http://icodeblog.com/2011/11/09/how-to-import-contacts-into-the-iphone-simulator/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 23:41:11 +0000</pubDate>
		<dc:creator><![CDATA[Marc Charbonneau]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Address Book]]></category>
		<category><![CDATA[AddressBook.framework]]></category>
		<category><![CDATA[Contacts]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=3614</guid>
		<description><![CDATA[If you&#8217;re working with AddressBook.framework chances are you&#8217;ll want to import your own data to test against when you&#8217;re in the simulator. Without being able to sync with iTunes or iCloud you may think you&#8217;re stuck entering in addresses manually; not only is that a huge pain, but there are probably lots of edge cases already in your address book you wouldn&#8217;t necessarily think of.
Fortunately there&#8217;s another option, with a tool called <a href="http://supercrazyawesome.com/">iPhone Backup Extractor</a>. Download it, run it  ...]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;re working with AddressBook.framework chances are you&#8217;ll want to import your own data to test against when you&#8217;re in the simulator. Without being able to sync with iTunes or iCloud you may think you&#8217;re stuck entering in addresses manually; not only is that a huge pain, but there are probably lots of edge cases already in your address book you wouldn&#8217;t necessarily think of.</p>
<p>Fortunately there&#8217;s another option, with a tool called <a href="http://supercrazyawesome.com/">iPhone Backup Extractor</a>. Download it, run it and click Read Backups (note that you&#8217;ll need to back up to iTunes, not iCloud). Select your device, and you should see a list of apps included in your backup. Choose the last item on the list, iOS Files, and extract it to your desktop. When it&#8217;s done take a look in the folder it created. You should find two files in the folder <strong>iOS Files/Library/AddressBook</strong>, <strong>AddressBook.sqlitedb</strong> and <strong>AddressBookImages.sqlitedb</strong>.</p>
<p>Next, open the simulator&#8217;s Application Support folder (in the Finder menu, choose <strong>Go</strong> -&gt; <strong>Go to Folder&#8230;</strong>, enter <strong>~/Library/Application Support/iPhone Simulator</strong>, and choose the SDK you&#8217;re working with) and drill down to <strong>Library/AddressBook</strong>. Quit the simulator if it&#8217;s open, delete everything in this directory, then copy the two files noted above from your backup. That&#8217;s it! If everything went well the next time you launch the simulator you should see all your contacts.</p>
<p>Pretty easy, really. If address book data is a major feature of your app, you might even want to have a few trusted beta testers send you their backups so you can test with their contacts. My experience is that there are a lot of unusual or invalid contacts floating around on people&#8217;s phones, and the more opportunity you have to test the better you&#8217;ll do once you release your app.</p>
<!-- Start Sociable --><div class="sociable"><ul class='clearfix'></ul><div onMouseout="fixOnMouseOut(this,event,'post-3614')" id="sociable-post-3614" style="display:none;">   

    <div style="top: auto; left: auto; display: block;" id="sociable">



		<div class="popup">

			<div class="content">

				<ul><li style="heigth:32px;width:32px"><a title="Facebook" class="option1_32" style="background-position:-96px 0px" rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;t=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator"></a></li><li style="heigth:32px;width:32px"><a title="Myspace" class="option1_32" style="background-position:0px -32px" rel="nofollow" target="_blank" href="http://www.myspace.com/Modules/PostTo/Pages/?u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;t=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator"></a></li><li style="heigth:32px;width:32px"><a title="Twitter" class="option1_32" style="background-position:-288px -32px" rel="nofollow" target="_blank" href="http://twitter.com/intent/tweet?text=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator%20-%20http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F%20  SHARETAG"></a></li><li style="heigth:32px;width:32px"><a title="LinkedIn" class="option1_32" style="background-position:-288px 0px" rel="nofollow" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;title=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator&amp;source=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials&amp;summary=If%20you%27re%20working%20with%20AddressBook.framework%20chances%20are%20you%27ll%20want%20to%20import%20your%20own%20data%20to%20test%20against%20when%20you%27re%20in%20the%20simulator.%20Without%20being%20able%20to%20sync%20with%20iTunes%20or%20iCloud%20you%20may%20think%20you%27re%20stuck%20entering%20in%20addresses%20manually%3B%20not"></a></li><li style="heigth:32px;width:32px"><a title="Delicious" class="option1_32" style="background-position:-32px 0px" rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;title=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator&amp;notes=If%20you%27re%20working%20with%20AddressBook.framework%20chances%20are%20you%27ll%20want%20to%20import%20your%20own%20data%20to%20test%20against%20when%20you%27re%20in%20the%20simulator.%20Without%20being%20able%20to%20sync%20with%20iTunes%20or%20iCloud%20you%20may%20think%20you%27re%20stuck%20entering%20in%20addresses%20manually%3B%20not"></a></li><li style="heigth:32px;width:32px"><a title="Digg" class="option1_32" style="background-position:-64px 0px" rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;title=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator&amp;bodytext=If%20you%27re%20working%20with%20AddressBook.framework%20chances%20are%20you%27ll%20want%20to%20import%20your%20own%20data%20to%20test%20against%20when%20you%27re%20in%20the%20simulator.%20Without%20being%20able%20to%20sync%20with%20iTunes%20or%20iCloud%20you%20may%20think%20you%27re%20stuck%20entering%20in%20addresses%20manually%3B%20not"></a></li><li style="heigth:32px;width:32px"><a title="Reddit" class="option1_32" style="background-position:-128px -32px" rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;title=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator"></a></li><li style="heigth:32px;width:32px"><a title="StumbleUpon" class="option1_32" style="background-position:-224px -32px" rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&title=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator"></a></li><li style="heigth:32px;width:32px"><a title="Google Bookmarks" class="option1_32" style="background-position:-192px 0px" rel="nofollow" target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;title=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator&amp;annotation=If%20you%27re%20working%20with%20AddressBook.framework%20chances%20are%20you%27ll%20want%20to%20import%20your%20own%20data%20to%20test%20against%20when%20you%27re%20in%20the%20simulator.%20Without%20being%20able%20to%20sync%20with%20iTunes%20or%20iCloud%20you%20may%20think%20you%27re%20stuck%20entering%20in%20addresses%20manually%3B%20not"></a></li><li style="heigth:32px;width:32px"><a title="HackerNews" class="option1_32" style="background-position:-256px 0px" rel="nofollow" target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;t=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator"></a></li><li style="heigth:32px;width:32px"><a title="MSNReporter" class="option1_32" style="background-position:-352px 0px" rel="nofollow" target="_blank" href="http://reporter.es.msn.com/?fn=contribute&amp;Title=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator&amp;URL=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;cat_id=6&amp;tag_id=31&amp;Remark=If%20you%27re%20working%20with%20AddressBook.framework%20chances%20are%20you%27ll%20want%20to%20import%20your%20own%20data%20to%20test%20against%20when%20you%27re%20in%20the%20simulator.%20Without%20being%20able%20to%20sync%20with%20iTunes%20or%20iCloud%20you%20may%20think%20you%27re%20stuck%20entering%20in%20addresses%20manually%3B%20not"></a></li><li style="heigth:32px;width:32px"><a title="BlinkList" class="option1_32" style="background-position:0px 0px" rel="nofollow" target="_blank" href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&amp;Url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;Title=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator"></a></li><li style="heigth:32px;width:32px"><a title="Sphinn" class="option1_32" style="background-position:-192px -32px" rel="nofollow" target="_blank" href="http://sphinn.com/index.php?c=post&amp;m=submit&amp;link=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F"></a></li><li style="heigth:32px;width:32px"><a title="Posterous" class="option1_32" style="background-position:-64px -32px" rel="nofollow" target="_blank" href="http://posterous.com/share?linkto=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;title=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator&amp;selection=If%20you%27re%20working%20with%20AddressBook.framework%20chances%20are%20you%27ll%20want%20to%20import%20your%20own%20data%20to%20test%20against%20when%20you%27re%20in%20the%20simulator.%20Without%20being%20able%20to%20sync%20with%20iTunes%20or%20iCloud%20you%20may%20think%20you%27re%20stuck%20entering%20in%20addresses%20manually%3B%20not"></a></li><li style="heigth:32px;width:32px"><a title="Tumblr" class="option1_32" style="background-position:-256px -32px" rel="nofollow" target="_blank" href="http://www.tumblr.com/share?v=3&amp;u=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;t=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator&amp;s=If%20you%27re%20working%20with%20AddressBook.framework%20chances%20are%20you%27ll%20want%20to%20import%20your%20own%20data%20to%20test%20against%20when%20you%27re%20in%20the%20simulator.%20Without%20being%20able%20to%20sync%20with%20iTunes%20or%20iCloud%20you%20may%20think%20you%27re%20stuck%20entering%20in%20addresses%20manually%3B%20not"></a></li><li style="heigth:32px;width:32px"><a title="email" class="option1_32" style="background-position:-160px 0px" rel="nofollow" target="_blank" href="https://mail.google.com/mail/?view=cm&fs=1&to&su=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator&body=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&ui=2&tf=1&shva=1"></a></li><li style="heigth:32px;width:32px"><a title="Google Reader" class="option1_32" style="background-position:-224px 0px" rel="nofollow" target="_blank" href="http://www.google.com/reader/link?url=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;title=How%20to%20import%20contacts%20into%20the%20iPhone%20Simulator&amp;srcURL=http%3A%2F%2Fwww.icodeblog.com%2F2011%2F11%2F09%2Fhow-to-import-contacts-into-the-iphone-simulator%2F&amp;srcTitle=iPhone+Programming+Tutorials+iPhone+Programming+Tutorials"></a></li><li style="heigth:32px;width:32px"><a class="option1_32" style="cursor:pointer;background-position:-128px 0px" rel="nofollow" title="Add to favorites - doesn't work in Chrome"  onClick="javascript:AddToFavorites();"></a></li><li style="heigth:32px;width:32px"><a style="cursor:poainter" rel="nofollow"   onMouseOver="more(this,'post-3614')"><img style='margin-top:9px' src='/wp-content/plugins/sociable/images/more.png'></a></li></ul>			

			</div>        

		  <a style="cursor:pointer" onclick="hide_sociable('post-3614',true)" class="close">

		  <img onclick="hide_sociable('post-3614',true)" title="close" src="/wp-content/plugins/sociable/images/closelabel.png">

		  </a>

		</div>

	</div> 

  </div></div><div class='sociable' style='float:none'><ul class='clearfix'><li id="Twitter_Counter"><a href="https://twitter.com/share" data-text="How to import contacts into the iPhone Simulator - http://icodeblog.com/2011/11/09/how-to-import-contacts-into-the-iphone-simulator/" data-url="http://icodeblog.com/2011/11/09/how-to-import-contacts-into-the-iphone-simulator/" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></li><li id="Facebook_Counter"><iframe src="http://www.facebook.com/plugins/like.php?href=http://icodeblog.com/2011/11/09/how-to-import-contacts-into-the-iphone-simulator/&send=false&layout=button_count&show_faces=false&action=like&colorscheme=light&font" scrolling="no" frameborder="0" style="border:none; overflow:hidden;height:32px;width:100px" allowTransparency="true"></iframe></li><li id="Google_p"><g:plusone annotation="bubble" href="/2011/11/09/how-to-import-contacts-into-the-iphone-simulator/" size="medium"></g:plusone></li><li id="LinkedIn_Counter"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="http://icodeblog.com/2011/11/09/how-to-import-contacts-into-the-iphone-simulator/" data-counter="right"></script></li></ul></div><!-- End Sociable -->]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2011/11/09/how-to-import-contacts-into-the-iphone-simulator/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>
