<?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; iPhone Coding</title>
	<atom:link href="/tag/iphone-coding/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=3.9.1</generator>
	<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- 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>- 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>- 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>
]]></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>Disable the iPhone&#8217;s Front Camera</title>
		<link>http://icodeblog.com/2011/08/23/disable-the-iphones-front-camera/</link>
		<comments>http://icodeblog.com/2011/08/23/disable-the-iphones-front-camera/#comments</comments>
		<pubDate>Tue, 23 Aug 2011 20:44:00 +0000</pubDate>
		<dc:creator><![CDATA[Marc Charbonneau]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Camera]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[iPhone Coding]]></category>
		<category><![CDATA[iphone programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=3334</guid>
		<description><![CDATA[The iPhone 4&#8242;s front camera is limited to 640&#215;480 resolution. Although handy for video conferencing, for some apps that&#8217;s to small to yield a usable photo. Unfortunately the UIImagePickerController class does not have an option to restrict the user from using the front camera. Although you can check the size of the photo after the user is finished, it&#8217;s not great user experience to reject it after they go through the entire process of taking a photo.
One option is to  ...]]></description>
				<content:encoded><![CDATA[<p>The iPhone 4&#8242;s front camera is limited to 640&#215;480 resolution. Although handy for video conferencing, for some apps that&#8217;s to small to yield a usable photo. Unfortunately the UIImagePickerController class does not have an option to restrict the user from using the front camera. Although you can check the size of the photo after the user is finished, it&#8217;s not great user experience to reject it after they go through the entire process of taking a photo.</p>
<p>One option is to replace the standard camera controls with a custom interface, but that&#8217;s a whole lot of work if you just want to prevent the user from taking a photo with the front camera. Fortunately there&#8217;s another option: put a transparent button over the &#8220;switch camera&#8221; button, which will intercept touch events and show an alert dialog. It sounds simple, but as you&#8217;ll see there are a few tricks to actually getting this to work.</p>
<p>We&#8217;re going to use UIImagePickerController&#8217;s <strong>cameraOverlayView</strong> property to add our button to the view hierarchy. We can&#8217;t simply provide a UIButton object though. In the latest iOS SDK, cameraOverlayView is automatically resized to fill the entire screen, while we only want to cover a small corner of it. Instead, we&#8217;re going to put the button inside a UIView subclass that will be used for layout and a few other tasks. Go ahead and create this UIView subclass in your project, call it <strong>ELCCameraOverlayView</strong>, and delete any methods the Xcode template includes by default.</p>
<p>We&#8217;ll need a button, so let&#8217;s start by giving our new subclass a UIButton instance variable named <strong>_button</strong> with a corresponding <strong>button</strong> property. Declare this as you&#8217;d declare any synthesized property, but let&#8217;s override the default setter method to also add it to the view hierarchy.</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>setButton<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIButton <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>button;
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> _button <span style="color: #002200;">!=</span> button <span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>_button removeFromSuperview<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>_button release<span style="color: #002200;">&#93;</span>;
        _button <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>button retain<span style="color: #002200;">&#93;</span>;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> button <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span> <span style="color: #002200;">&#41;</span>
        	<span style="color: #002200;">&#91;</span>self addSubview<span style="color: #002200;">:</span>button<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>You might create the button in another class (such as a view controller) and assign it to our custom class, but you can also create a standard button in your initWithFrame: method. Note that we still have to call <strong>addSubview:</strong> here as we&#8217;re not using the property accessor method (which is discouraged in init 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;">id</span><span style="color: #002200;">&#41;</span>initWithFrame<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGRect<span style="color: #002200;">&#41;</span>frame;
<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 initWithFrame<span style="color: #002200;">:</span>frame<span style="color: #002200;">&#93;</span> <span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        _button <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIButton alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>CGRectMake<span style="color: #002200;">&#40;</span> 240.0f, 0.0f, 80.0f, 80.0f <span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>self addSubview<span style="color: #002200;">:</span>_button<span style="color: #002200;">&#93;</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>With the button in place, let&#8217;s move on to intercepting touch events which would normally go to the &#8220;switch cameras&#8221; button. We can do this by overriding the UIView methods which are called to determine if an event occurred within a view&#8217;s frame or not. Just check to see if the event took place within the button&#8217;s frame rectangle.</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>UIView <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>hitTest<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGPoint<span style="color: #002200;">&#41;</span>point withEvent<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIEvent <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event;
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> <span style="color: #002200;">&#91;</span>super hitTest<span style="color: #002200;">:</span>point withEvent<span style="color: #002200;">:</span>event<span style="color: #002200;">&#93;</span> <span style="color: #002200;">==</span> self.button <span style="color: #002200;">&#41;</span>
        <span style="color: #a61390;">return</span> self.button;
&nbsp;
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>pointInside<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGPoint<span style="color: #002200;">&#41;</span>point withEvent<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIEvent <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event;
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> CGRectContainsPoint<span style="color: #002200;">&#40;</span> self.button.frame, point <span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#41;</span>
        <span style="color: #a61390;">return</span> <span style="color: #a61390;">YES</span>;
&nbsp;
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">NO</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>It may seem like we&#8217;re almost done at this point. If you set the camera overlay view to an instance of this class you&#8217;ll see the &#8220;switch camera&#8221; button should no longer work, and if you give the button an action method you can pop up an alert message telling users not to use the front camera. However, if you rotate the phone to landscape mode, you&#8217;ll notice that while the &#8220;switch camera&#8221; button is re-positioned, our custom button is not! To see what I mean, try setting a custom background color on our button so you can see it on screen.</p>
<p>This is a tricky problem. Unlike UIViewController, our UIView subclass does not have any way of telling when the interface orientation is changed. This doesn&#8217;t even matter though, since UIImagePickerController doesn&#8217;t actually change its interface orientation, it simply re-arranges the camera buttons while remaining in UIInterfaceOrientationPortrait! </p>
<p>The way I&#8217;ve solved this problem is to use the accelerometer to determine the device orientation. It might sound complicated, but it&#8217;s actually not a lot of work. Start by adding a new instance variable <strong>_interfaceOrientation</strong> and property <strong>interfaceOrientation</strong> to your class, of type <strong>UIInterfaceOrientation</strong>. We&#8217;ll also override its setter method to call <strong>setNeedsLayout</strong> whenever its changed.</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>setInterfaceOrientation<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIInterfaceOrientation<span style="color: #002200;">&#41;</span>interfaceOrientation;
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> _interfaceOrientation <span style="color: #002200;">!=</span> interfaceOrientation <span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        _interfaceOrientation <span style="color: #002200;">=</span> interfaceOrientation;
        <span style="color: #002200;">&#91;</span>self setNeedsLayout<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Now let&#8217;s move the button whenever the orientation changes, and implement the required <strong>UIAccelerometerDelegate</strong> 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>layoutSubviews;
<span style="color: #002200;">&#123;</span>
    CGFloat width <span style="color: #002200;">=</span> CGRectGetWidth<span style="color: #002200;">&#40;</span> self.button.frame <span style="color: #002200;">&#41;</span>;
    CGFloat height <span style="color: #002200;">=</span> CGRectGetHeight<span style="color: #002200;">&#40;</span> self.button.frame <span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #a61390;">switch</span> <span style="color: #002200;">&#40;</span> self.interfaceOrientation <span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">case</span> UIInterfaceOrientationPortrait<span style="color: #002200;">:</span>
        <span style="color: #a61390;">case</span> UIInterfaceOrientationPortraitUpsideDown<span style="color: #002200;">:</span>
            self.button.frame <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span> CGRectGetMaxX<span style="color: #002200;">&#40;</span> self.bounds <span style="color: #002200;">&#41;</span> <span style="color: #002200;">-</span> width, 0.0f, width, height <span style="color: #002200;">&#41;</span>;
            <span style="color: #a61390;">break</span>;
        <span style="color: #a61390;">case</span> UIInterfaceOrientationLandscapeRight<span style="color: #002200;">:</span>
            self.button.frame <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span> CGRectGetMaxX<span style="color: #002200;">&#40;</span> self.bounds <span style="color: #002200;">&#41;</span> <span style="color: #002200;">-</span> width, CGRectGetMaxY<span style="color: #002200;">&#40;</span> self.bounds <span style="color: #002200;">&#41;</span> <span style="color: #002200;">-</span> height <span style="color: #002200;">-</span> 50.0f, width, height <span style="color: #002200;">&#41;</span>;
            <span style="color: #a61390;">break</span>;
        <span style="color: #a61390;">case</span> UIInterfaceOrientationLandscapeLeft<span style="color: #002200;">:</span>
            self.button.frame <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span> 0.0f, 0.0f, width, height <span style="color: #002200;">&#41;</span>;
            <span style="color: #a61390;">break</span>;
    <span style="color: #002200;">&#125;</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>accelerometer<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIAccelerometer <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>accelerometer didAccelerate<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIAcceleration <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>acceleration;
<span style="color: #002200;">&#123;</span> 
	CGFloat x <span style="color: #002200;">=</span> <span style="color: #002200;">-</span><span style="color: #002200;">&#91;</span>acceleration x<span style="color: #002200;">&#93;</span>; 
	CGFloat y <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>acceleration y<span style="color: #002200;">&#93;</span>; 
	CGFloat angle <span style="color: #002200;">=</span> <span style="color: #a61390;">atan2</span><span style="color: #002200;">&#40;</span>y, x<span style="color: #002200;">&#41;</span>; 
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> angle &gt;<span style="color: #002200;">=</span> <span style="color: #002200;">-</span>2.25f <span style="color: #002200;">&amp;&amp;</span> angle &lt;<span style="color: #002200;">=</span> <span style="color: #002200;">-</span>0.25f <span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
        self.interfaceOrientation <span style="color: #002200;">=</span> UIInterfaceOrientationPortrait;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> angle &gt;<span style="color: #002200;">=</span> <span style="color: #002200;">-</span>1.75f <span style="color: #002200;">&amp;&amp;</span> angle &lt;<span style="color: #002200;">=</span> 0.75f <span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
        self.interfaceOrientation <span style="color: #002200;">=</span> UIInterfaceOrientationLandscapeRight;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span> angle &gt;<span style="color: #002200;">=</span> 0.75f <span style="color: #002200;">&amp;&amp;</span> angle &lt;<span style="color: #002200;">=</span> 2.25f <span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
        self.interfaceOrientation <span style="color: #002200;">=</span> UIInterfaceOrientationPortraitUpsideDown;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> angle &lt;<span style="color: #002200;">=</span> <span style="color: #002200;">-</span>2.25f || angle &gt;<span style="color: #002200;">=</span> 2.25f <span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
        self.interfaceOrientation <span style="color: #002200;">=</span> UIInterfaceOrientationLandscapeLeft;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>We&#8217;re almost done! Just make sure to start and stop the accelerometer in your init and dealloc 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;">id</span><span style="color: #002200;">&#41;</span>initWithFrame<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGRect<span style="color: #002200;">&#41;</span>frame;
<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 initWithFrame<span style="color: #002200;">:</span>frame<span style="color: #002200;">&#93;</span> <span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        _interfaceOrientation <span style="color: #002200;">=</span> UIInterfaceOrientationPortrait;
        _button <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIButton alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>CGRectMake<span style="color: #002200;">&#40;</span> 240.0f, 0.0f, 80.0f, 80.0f <span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIAccelerometer sharedAccelerometer<span style="color: #002200;">&#93;</span> setDelegate<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>self addSubview<span style="color: #002200;">:</span>_button<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #a61390;">return</span> self;
<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>dealloc;
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIAccelerometer sharedAccelerometer<span style="color: #002200;">&#93;</span> setDelegate<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>_button release<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Finished! If you haven&#8217;t tested your overlay yet, you can add it to your UIImagePickerController as so.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">UIImagePickerController <span style="color: #002200;">*</span>controller <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIImagePickerController alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
ELCCameraOverlayView <span style="color: #002200;">*</span>view <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>ELCCameraOverlayView alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>controller.view.frame<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>view.button addTarget<span style="color: #002200;">:</span>self action<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>selectFrontCamera<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> forControlEvents<span style="color: #002200;">:</span>UIControlEventTouchUpInside<span style="color: #002200;">&#93;</span>;
&nbsp;
controller.sourceType <span style="color: #002200;">=</span> UIImagePickerControllerSourceTypeCamera;
controller.cameraCaptureMode <span style="color: #002200;">=</span> UIImagePickerControllerCameraCaptureModePhoto;
controller.cameraDevice <span style="color: #002200;">=</span> UIImagePickerControllerCameraDeviceRear;
controller.delegate <span style="color: #002200;">=</span> self;
controller.cameraOverlayView <span style="color: #002200;">=</span> view;
&nbsp;
<span style="color: #002200;">&#91;</span>self.navigationController presentModalViewController<span style="color: #002200;">:</span>controller animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>controller release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>view release<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>Don&#8217;t forget to provide the button&#8217;s action method. You could show an alert, for instance.</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>selectFrontCamera<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: #400080;">NSString</span> <span style="color: #002200;">*</span>title <span style="color: #002200;">=</span> NSLocalizedString<span style="color: #002200;">&#40;</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Front Camera Disabled&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;&quot;</span> <span style="color: #002200;">&#41;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>message <span style="color: #002200;">=</span> NSLocalizedString<span style="color: #002200;">&#40;</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;The front camera does not have sufficient resolution.&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;&quot;</span> <span style="color: #002200;">&#41;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>button <span style="color: #002200;">=</span> NSLocalizedString<span style="color: #002200;">&#40;</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Okay&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;&quot;</span> <span style="color: #002200;">&#41;</span>;
    UIAlertView <span style="color: #002200;">*</span>alert <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIAlertView alloc<span style="color: #002200;">&#93;</span> initWithTitle<span style="color: #002200;">:</span>title message<span style="color: #002200;">:</span>message delegate<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> cancelButtonTitle<span style="color: #002200;">:</span>button otherButtonTitles<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span>alert show<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>alert release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>I&#8217;ve uploaded the <a href="https://gist.github.com/1166388">complete ELCCameraOverlayView class files here</a>. Leave a comment if you have any questions!</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2011/08/23/disable-the-iphones-front-camera/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>iPhone Game Programming Series: Blackjack &#8211; Part 1: The Deck</title>
		<link>http://icodeblog.com/2010/09/09/iphone-game-programming-series-blackjack-part-1-the-deck/</link>
		<comments>http://icodeblog.com/2010/09/09/iphone-game-programming-series-blackjack-part-1-the-deck/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 13:00:01 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Advanced]]></category>
		<category><![CDATA[blackjack]]></category>
		<category><![CDATA[card deck]]></category>
		<category><![CDATA[iphone card deck]]></category>
		<category><![CDATA[iPhone Coding]]></category>
		<category><![CDATA[iphone game]]></category>
		<category><![CDATA[iphone programming]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=2299</guid>
		<description><![CDATA[It has been quite some time since our last <a href="/2009/01/15/iphone-game-programming-tutorial-part-1/">iPhone video game series</a> and now we are ready to start a new one.  Given the success of our iTennis tutorial series, we will be following along the same line and create a game without using OpenGL ES.  If you are interested in OpenGL ES programming, check out <a href="http://iphonedevelopment.blogspot.com/">Jeff Lamarche&#8217;s blog</a>, he&#8217;s super rad.  In this series we will be creating a simple Blackjack game with  ...]]></description>
				<content:encoded><![CDATA[<p>It has been quite some time since our last <a href="/2009/01/15/iphone-game-programming-tutorial-part-1/">iPhone video game series</a> and now we are ready to start a new one.  Given the success of our iTennis tutorial series, we will be following along the same line and create a game without using OpenGL ES.  If you are interested in OpenGL ES programming, check out <a href="http://iphonedevelopment.blogspot.com/">Jeff Lamarche&#8217;s blog</a>, he&#8217;s super rad.  In this series we will be creating a simple Blackjack game with the following features/functionality:</p>
<ul>
<li>Deck of cards</li>
<li>Basic Blackjack rules/logic</li>
<li>Dealer</li>
<li>Basic Dealer AI</li>
<li>Player</li>
<li>Controls for hit/stand</li>
<li>Audio</li>
<li>User Interface</li>
</ul>
<p>In this first part of the series we are going to introduce the core of the game; the deck.  We will be building a very generic deck of cards that could be used in any type of card game.  The deck will be portable enough to just drag and drop into any project that requires a deck of cards.  So, let&#8217;s begin by creating a view based application and calling it ICBBlackjack.</p>
<h2>Creating A Card Object</h2>
<p>Before we can create the deck, we need to create a card.  Before we dig into the code, let me explain how a card object will work.  A card has 2 properties that we care about.  They are suit and value.  Suit is pretty obvious (Hearts, Diamonds, Spades, Clubs), but the value might not be what you&#8217;d expect.  For the cases of the numeric cards, the value is simply their value, however it changes a bit for the face cards and ace.</p>
<p>The Ace gets assigned a value of 1 (pretty obvious), while the face cards get values based on their ordering from the 10 card.  So a Jack = 11, Queen = 12, and King = 13.  Obviously this isn&#8217;t the case when playing a game like Blackjack, but we will let another class figure that out. For now, we will use the value as and identifier for the card.  Add a new class file to your project called <strong>Card.m</strong>.  Make sure you check the box to include the .h file. Open up Card.h and add the following code:</p>
<h3>Card.h</h3>

<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;">enum</span> <span style="color: #002200;">&#123;</span>
	Hearts,
	Diamonds,
	Spades,
	Clubs
<span style="color: #002200;">&#125;</span> Suit;
&nbsp;
<span style="color: #6e371a;">#define Ace   1</span>
<span style="color: #6e371a;">#define Jack  11</span>
<span style="color: #6e371a;">#define Queen 12</span>
<span style="color: #6e371a;">#define King  13</span>
&nbsp;
<span style="color: #a61390;">@interface</span> Card <span style="color: #002200;">:</span> <span style="color: #400080;">NSObject</span> <span style="color: #002200;">&#123;</span>
	NSInteger value;
	Suit suit;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic<span style="color: #002200;">&#41;</span> NSInteger value;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic<span style="color: #002200;">&#41;</span> Suit suit;
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span> initWithValue<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span> aValue suit<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>Suit<span style="color: #002200;">&#41;</span> aSuit;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>Ok, so a few things here to point out.  The first thing we see at the top is an enum.  The enum allows us to declare our own type called Suit.  We could have just as easily used constants, but the enum makes things a little more clear.  This allows us to do things like <strong>myCard.suit = Clubs</strong>.</p>
<p>Now, we define the &#8220;Special&#8221; values which will be assigned to the Ace and face cards.  Finally, we declare our value and suit properties and declare and init method to build a card with these values set.  Now, it&#8217;s time to implement our Card class.  Open Card.m and add the following code.</p>
<h3>Card.m</h3>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;Card.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> Card<span style="color: #002200;">&#40;</span>Private<span style="color: #002200;">&#41;</span>
&nbsp;
<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> valueAsString;
<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> suitAsString;
&nbsp;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> Card
&nbsp;
<span style="color: #a61390;">@synthesize</span> value,suit;
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span> initWithValue<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span> aValue suit<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>Suit<span style="color: #002200;">&#41;</span> aSuit <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</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;">&#123;</span>
		self.value <span style="color: #002200;">=</span> aValue;
		self.suit <span style="color: #002200;">=</span> aSuit;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<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> valueAsString <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">switch</span> <span style="color: #002200;">&#40;</span>self.value<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">case</span> Ace<span style="color: #002200;">:</span>
			<span style="color: #a61390;">return</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Ace&quot;</span>;
			<span style="color: #a61390;">break</span>;
		<span style="color: #a61390;">case</span> Jack<span style="color: #002200;">:</span>
			<span style="color: #a61390;">return</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Jack&quot;</span>;
			<span style="color: #a61390;">break</span>;
		<span style="color: #a61390;">case</span> Queen<span style="color: #002200;">:</span>
			<span style="color: #a61390;">return</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Queen&quot;</span>;
			<span style="color: #a61390;">break</span>;
		<span style="color: #a61390;">case</span> King<span style="color: #002200;">:</span>
			<span style="color: #a61390;">return</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;King&quot;</span>;
			<span style="color: #a61390;">break</span>;
		<span style="color: #a61390;">default</span><span style="color: #002200;">:</span>
			<span style="color: #a61390;">return</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>,self.value<span style="color: #002200;">&#93;</span>;
			<span style="color: #a61390;">break</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<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> suitAsString <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">switch</span> <span style="color: #002200;">&#40;</span>self.suit<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">case</span> Hearts<span style="color: #002200;">:</span>
			<span style="color: #a61390;">return</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Hearts&quot;</span>;
			<span style="color: #a61390;">break</span>;
		<span style="color: #a61390;">case</span> Diamonds<span style="color: #002200;">:</span>
			<span style="color: #a61390;">return</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Diamonds&quot;</span>;
			<span style="color: #a61390;">break</span>;
		<span style="color: #a61390;">case</span> Spades<span style="color: #002200;">:</span>
			<span style="color: #a61390;">return</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Spades&quot;</span>;
			<span style="color: #a61390;">break</span>;
		<span style="color: #a61390;">case</span> Clubs<span style="color: #002200;">:</span>
			<span style="color: #a61390;">return</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Clubs&quot;</span>;
			<span style="color: #a61390;">break</span>;
		<span style="color: #a61390;">default</span><span style="color: #002200;">:</span>
			<span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
			<span style="color: #a61390;">break</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<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> description <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">return</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;%@ of %@&quot;</span>,
			<span style="color: #002200;">&#91;</span>self valueAsString<span style="color: #002200;">&#93;</span>,
			<span style="color: #002200;">&#91;</span>self suitAsString<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>Wow, so this looks like a lot of overkill.  The truth is, you only need the init method that I created.  The description method allows us to overwrite the printing method for a card and gives us pretty output.  The other 2 methods are simply help methods for it (we have declared them as private at the top).  You can choose to omit them if you like, but make debugging a lot easier.  When you do something like NSLog(@&#8221;%@&#8221;,myCard), it will print &#8220;Ace of Spades&#8221;.  Great, now you have a Card object to work with.  Now we just need to create 52 of these puppies and we are on our way to hundreds of card games.</p>
<h2>Creating The Deck</h2>
<p>The deck of cards is fairly straight forward.  First off, we need an array of cards.  The card needs to have 3 methods implemented for correct functionality.  They are draw, shuffle, and cardsRemaining.  The reason the cardsRemaining method is needed is to prevent users from trying to draw cards from an empty deck (we will discuss this in a bit).  Add a new class file to your project called <strong>Deck.m </strong>and add the following code to Deck.h:</p>
<h3>Deck.h</h3>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;Card.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> Deck <span style="color: #002200;">:</span> <span style="color: #400080;">NSObject</span> <span style="color: #002200;">&#123;</span>
&nbsp;
<span style="color: #a61390;">@private</span>
	<span style="color: #400080;">NSMutableArray</span> <span style="color: #002200;">*</span>cards;
<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> shuffle;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>Card <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> draw;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span> cardsRemaining;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>A few things I want to point out.  First, we import Card.h.  Normally we would import the models in the .m file if they are not needed in the header.  However, we need to declare the draw method which returns a Card object.  So, we include the import statement here.</p>
<p>The next thing I want to point out is we have marked the cards array as private.  We don&#8217;t want anyone mucking around in our deck without going through our methods.  The reason for this is to prevent synchronization issues where someone modifies the deck without notifying the class.  Kinda trivial, but good practice non the less.  Now for the implementation.  Add the following code to Deck.m.</p>
<h3>Deck.m</h3>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;Deck.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> Deck
&nbsp;
<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>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;">&#123;</span>
		cards <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: #a61390;">for</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> suit <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>; suit <span style="color: #002200;">&amp;</span>lt;<span style="color: #002200;">=</span> <span style="color: #2400d9;">3</span>; suit<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
			<span style="color: #a61390;">for</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> value <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span>; value <span style="color: #002200;">&amp;</span>lt;<span style="color: #002200;">=</span> <span style="color: #2400d9;">13</span>; value<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
				Card <span style="color: #002200;">*</span>card <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>Card alloc<span style="color: #002200;">&#93;</span> initWithValue<span style="color: #002200;">:</span>value suit<span style="color: #002200;">:</span>suit<span style="color: #002200;">&#93;</span>;
				<span style="color: #002200;">&#91;</span>cards addObject<span style="color: #002200;">:</span>card<span style="color: #002200;">&#93;</span>;
				<span style="color: #002200;">&#91;</span>card release<span style="color: #002200;">&#93;</span>;
			<span style="color: #002200;">&#125;</span>
		<span style="color: #002200;">&#125;</span>
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">/*
 * Random sort used from this blog post
 * http://zaldzbugz.wordpress.com/2010/07/16/randomly-sort-nsarray/
 */</span>
<span style="color: #a61390;">int</span> randomSort<span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span> obj1, <span style="color: #a61390;">id</span> obj2, <span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>context <span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// returns random number -1 0 1</span>
	<span style="color: #a61390;">return</span> <span style="color: #002200;">&#40;</span>arc4random<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">%</span>3 <span style="color: #002200;">-</span> <span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</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> shuffle <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">for</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> x <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>; x <span style="color: #002200;">&amp;</span>lt; <span style="color: #2400d9;">500</span>; x<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>cards sortUsingFunction<span style="color: #002200;">:</span>randomSort context<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>Card <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> draw <span style="color: #002200;">&#123;</span>
 	<span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self cardsRemaining<span style="color: #002200;">&#93;</span> <span style="color: #002200;">&amp;</span>gt; <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		Card <span style="color: #002200;">*</span>card <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>cards lastObject<span style="color: #002200;">&#93;</span> retain<span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#91;</span>cards removeLastObject<span style="color: #002200;">&#93;</span>;
		<span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>card autorelease<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #400080;">NSException</span><span style="color: #002200;">*</span> myException <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSException</span>
		exceptionWithName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;OutOfCardsException&quot;</span>
		reason<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Tried to draw a card from a deck with 0 cards.&quot;</span>
		userInfo<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #a61390;">@throw</span> myException;
<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> cardsRemaining <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>cards count<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: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> description <span style="color: #002200;">&#123;</span>
	<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>desc <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;Deck with %d cards<span style="color: #2400d9;">\n</span>&quot;</span>,<span style="color: #002200;">&#91;</span>self cardsRemaining<span style="color: #002200;">&#93;</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> x <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>; x <span style="color: #002200;">&amp;</span>lt; <span style="color: #002200;">&#91;</span>self cardsRemaining<span style="color: #002200;">&#93;</span>; x<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		desc <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>desc stringByAppendingFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@<span style="color: #2400d9;">\n</span>&quot;</span>,<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>cards objectAtIndex<span style="color: #002200;">:</span>x<span style="color: #002200;">&#93;</span> description<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">return</span> desc;
<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> dealloc <span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>cards release<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>Ok, this file needs a little more explanation.  First, we see the init method has been implemented.  There are 2 for loops.  The outer loop is from 0 to 3 representing the suit of each card.  Basically, we want to create 13 cards for each of the 4 suits.  The inner loop is from 1 to 13 representing the card&#8217;s value.  We simply instantiate a Card object with the suit and value and add it to the cards array. Let&#8217;s chat about each of the methods.</p>
<p><strong>Shuffle</strong></p>
<p>The shuffle method simply sorts the array based on a random number.  If we do it once, the deck will barely be shuffled, which makes sense.  So, I have randomly sorted the array 500 times to ensure that it has been effectively shuffled.  Note: I stole the randomSort method from http://zaldzbugz.wordpress.com/2010/07/16/randomly-sort-nsarray/ based on a quick/lazy Google search, but it&#8217;s a pretty common way of accomplishing this task.</p>
<p><strong>Draw</strong></p>
<p>We first check to see if the deck is empty. If it&#8217;s not, we retain the last object, remove it from the array and return an auto release of it.  It will be up to the caller to retain the Card.  Here is something you don&#8217;t see everyday, we are throwing an exception if the user tries to draw from an empty deck.  Kind of a jerk move, but it will ensure that they check the cardsRemaining before performing a draw.  Again, not totally necessary, but good practice.</p>
<p><strong>cardsRemaining</strong></p>
<p>Returns the length of the cards array  I override the description method in this class to print out the deck in its entirety.  Again, this is very useful for debugging.  Finally, we rock the memory management and release our card deck array when our deck gets cleaned up.</p>
<h2>Sample Run/Output</h2>
<p>Here is a simple example of how to create a deck, shuffle, and draw.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">        Deck <span style="color: #002200;">*</span>d <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>Deck alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>,d<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>d shuffle<span style="color: #002200;">&#93;</span>;
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>,d<span style="color: #002200;">&#41;</span>;
&nbsp;
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Drew Card: %@&quot;</span>,<span style="color: #002200;">&#91;</span>d draw<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Drew Card: %@&quot;</span>,<span style="color: #002200;">&#91;</span>d draw<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Drew Card: %@&quot;</span>,<span style="color: #002200;">&#91;</span>d draw<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Drew Card: %@&quot;</span>,<span style="color: #002200;">&#91;</span>d draw<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>,d<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>d release<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>The output is a little long, so I&#8217;ll just past some snippets of it.  You can run this for yourself to see the full output.</p>
<pre>Deck with 52 cards
Ace of Hearts
2 of Hearts
3 of Hearts
4 of Hearts
5 of Hearts
6 of Hearts
7 of Hearts
8 of Hearts
9 of Hearts
10 of Hearts
Jack of Hearts
Queen of Hearts
King of Hearts
Ace of Diamonds
2 of Diamonds
3 of Diamonds
...
(After shuffle)
Deck with 52 cards
King of Diamonds
6 of Hearts
5 of Spades
9 of Clubs
2 of Diamonds
8 of Clubs
7 of Hearts
Ace of Clubs
10 of Diamonds
Jack of Diamonds
8 of Spades
6 of Diamonds
Ace of Spades
3 of Spades
...
2010-09-07 14:56:37.953 ICBBlackJack[5465:207] Drew Card: Queen of Spades
2010-09-07 14:56:37.953 ICBBlackJack[5465:207] Drew Card: 9 of Spades
2010-09-07 14:56:37.954 ICBBlackJack[5465:207] Drew Card: 9 of Hearts
2010-09-07 14:56:37.955 ICBBlackJack[5465:207] Drew Card: Queen of Clubs

Deck with 48 cards
King of Diamonds
6 of Hearts
5 of Spades
9 of Clubs
2 of Diamonds
8 of Clubs
7 of Hearts
Ace of Clubs
10 of Diamonds
Jack of Diamonds
8 of Spades
6 of Diamonds
Ace of Spades</pre>
<p>Note that drawing a card pulls from the end of the array.  It doesn&#8217;t matter if you pull from the front or the back, just make sure it&#8217;s consistent.</p>
<h2>Conclusion</h2>
<p><a href="/wp-content/uploads/2010/09/ICBBlackJack1.zip">Click Here To Download The Code For This Tutorial</a></p>
<p>And there you have it! A fully functional deck of cards.  Please be sure to join me next time when we will start implementing the dealer and some basic Blackjack logic.  <a href="/wp-content/uploads/2010/09/ICBBlackJack1.zip">Click Here To Download The Code For This Tutorial</a> Feel free to post questions in the comments section or <a href="http://twitter.com/brandontreb">@reply them to me on Twitter</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2010/09/09/iphone-game-programming-series-blackjack-part-1-the-deck/feed/</wfw:commentRss>
		<slash:comments>40</slash:comments>
		</item>
		<item>
		<title>iPhone Coding &#8211; Turbo Charging Your Apps With NSOperation</title>
		<link>http://icodeblog.com/2010/03/04/iphone-coding-turbo-charging-your-apps-with-nsoperation/</link>
		<comments>http://icodeblog.com/2010/03/04/iphone-coding-turbo-charging-your-apps-with-nsoperation/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 19:28:18 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Advanced]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[iPhone Coding]]></category>
		<category><![CDATA[nosoperationqueue]]></category>
		<category><![CDATA[nsinvocationoperation]]></category>
		<category><![CDATA[nsoperation]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=1792</guid>
		<description><![CDATA[<p>So, let's face it, MANY applications in the app store are "Clunky".  They have jittery interfaces, poor scrolling performance, and the UI tends to lock up at times.  The reason? DOING ANYTHING OTHER THAN INTERFACE MANIPULATION IN THE MAIN APPLICATION THREAD!</p>

<p>What do I mean by this? Well, I am essentially talking about multithreading your application.  If you don't know what is meant by multithreading, I suggest you read up on it and return to this post.  Let's dig in and I'll give you an example of the problem.</p>]]></description>
				<content:encoded><![CDATA[<h4>Introduction</h4>
<p>So, let&#8217;s face it, MANY applications in the app store are &#8220;Clunky&#8221;.  They have jittery interfaces, poor scrolling performance, and the UI tends to lock up at times.  The reason? DOING ANYTHING OTHER THAN INTERFACE MANIPULATION IN THE MAIN APPLICATION THREAD!</p>
<p>What do I mean by this? Well, I am essentially talking about multithreading your application.  If you don&#8217;t know what is meant by multithreading, I suggest you <a href="http://en.wikipedia.org/wiki/Multithreading">read up on it</a> and return to this post OR don&#8217;t worry about it because you don&#8217;t need much threading knowledge for this tutorial.  Let&#8217;s dig in and I&#8217;ll give you an example of the problem.</p>
<h4>The Problem</h4>
<p>When you create an application, the iPhone spawns a new process containing the main thread of your application.  All of interface components are run inside of this thread (table views, tab bars, alerts, etc&#8230;).  At some point in your application, you will want to populate these views with data.  This data can be retrieved from the disk, the web, a database, etc&#8230; The problem is: How do you efficiently load this data into your interface while still allowing the user to have control of the application.</p>
<p>Many applications in the store simply &#8216;freeze&#8217; while their application data is being loaded.  This could be anywhere from a tenth of a second to much longer. Even the smallest amount of time is noticeable to the user.</p>
<p>Now, don&#8217;t get me wrong, I am not talking about applications that display  a loading message on the screen while the data populates.  In most cases, this is acceptable, but can not be done effectively unless the data is loaded in another thread besides the main one.</p>
<p>Here is a look at the application we will be creating today:</p>
<p><img class="alignnone size-full wp-image-1806" title="Screen shot 2010-03-04 at 12.15.47 PM" src="/wp-content/uploads/2010/03/Screen-shot-2010-03-04-at-12.15.47-PM1.png" alt="" width="414" height="770" /></p>
<p>Let&#8217;s take a look at the incorrect way to load data into a UITableView from data loaded from the web.   The example below reads a plist file from icodeblog.com containing 10,000 entries and populates a UITableView with those entries.  This happens when the user presses the &#8220;Load&#8221; button.</p>
<h3><span style="color: #ff0000;">Wrong (<a href="/wp-content/uploads/2010/03/NSOperationTableWRONG1.zip"><span style="color: #ff0000;">download this code here to see for yourself</span></a>)</span></h3>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> RootViewController
<span style="color: #a61390;">@synthesize</span> array;
&nbsp;
<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>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">/* Adding the button */</span>
    self.navigationItem.rightBarButtonItem <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIBarButtonItem alloc<span style="color: #002200;">&#93;</span> initWithTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Load&quot;</span>
        style<span style="color: #002200;">:</span>UIBarButtonItemStyleDone
        target<span style="color: #002200;">:</span>self
        action<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>loadData<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">/* Initialize our array */</span>
    <span style="color: #400080;">NSMutableArray</span> <span style="color: #002200;">*</span>_array <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> initWithCapacity<span style="color: #002200;">:</span><span style="color: #2400d9;">10000</span><span style="color: #002200;">&#93;</span>;
    self.array <span style="color: #002200;">=</span> _array;
    <span style="color: #002200;">&#91;</span>_array release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// Fires when the user presses the load button</span>
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> loadData <span style="color: #002200;">&#123;</span>
&nbsp;
    <span style="color: #11740a; font-style: italic;">/* Grab web data */</span>
    <span style="color: #400080;">NSURL</span> <span style="color: #002200;">*</span>dataURL <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/samples/nsoperation/data.plist&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>tmp_array <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithContentsOfURL<span style="color: #002200;">:</span>dataURL<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">/* Populate our array with the web data */</span>
    <span style="color: #a61390;">for</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>str <span style="color: #a61390;">in</span> tmp_array<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>self.array addObject<span style="color: #002200;">:</span>str<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #11740a; font-style: italic;">/* reload the table */</span>
    <span style="color: #002200;">&#91;</span>self.tableView reloadData<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#pragma mark Table view methods</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: #002200;">&#91;</span>self.array count<span style="color: #002200;">&#93;</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>
&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;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>;
    <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>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> autorelease<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #11740a; font-style: italic;">/* Display the text of the array */</span>
    <span style="color: #002200;">&#91;</span>cell.textLabel setText<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self.array objectAtIndex<span style="color: #002200;">:</span>indexPath.row<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">return</span> cell;
<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>dealloc <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>array release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>&#8220;Looks good to me&#8221;, you may say.  But that is incorrect.  If you run the code above, pressing the &#8220;Load&#8221; button will result in the interface &#8216;freezing&#8217; while the data is being retrieved from the web.  During that time, the user is unable to scroll or do anything since the main thread is off downloading data.</p>
<h4>About NSOperationQueue And NSOperation</h4>
<p>Before I show you the solution, I though I would bring you up to speed on NSOperation.</p>
<p>According to Apple&#8230;</p>
<blockquote><p>The <code>NSOperation</code> and <code>NSOperationQueue</code> classes alleviate much of the pain of multi-threading, allowing you to simply define your tasks, set any dependencies that exist, and fire them off. Each task, or <strong>operation</strong>, is represented by an instance of an <code>NSOperation</code> class; the <code>NSOperationQueue</code> class takes care of starting the operations, ensuring that they are run in the appropriate order, and accounting for any priorities that have been set.</p></blockquote>
<p>The way it works is, you create a new NSOperationQueue and add NSOperations to it.  The NSOperationQueue creates a new thread for each operation and runs them in the order they are added (or a specified order (advanced)).  It takes care of all of the autorelease pools and other garbage that gets confusing when doing multithreading and greatly simplifies the process.</p>
<p>Here is the process for using the NSOperationQueue.</p>
<ol>
<li>Instantiate a new NSOperationQueue object</li>
<li>Create an instance of your NSOperation</li>
<li>Add your operation to the queue</li>
<li>Release your operation</li>
</ol>
<p>There are a few ways to work with NSOperations.  Today, I will show you the simplest one: NSInvocationOperation.  NSInvocationOperation is a subclass of NSOperation which allows you to specify a target and selector that will run as an operation.</p>
<p>Here is an example of how to execute an NSInvocationOperation:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSOperationQueue</span> <span style="color: #002200;">*</span>queue <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSOperationQueue</span> new<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #400080;">NSInvocationOperation</span> <span style="color: #002200;">*</span>operation <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSInvocationOperation</span> alloc<span style="color: #002200;">&#93;</span> initWithTarget<span style="color: #002200;">:</span>self
    selector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>methodToCall<span style="color: #002200;">&#41;</span>
    object<span style="color: #002200;">:</span>objectToPassToMethod<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>queue addOperation<span style="color: #002200;">:</span>operation<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>operation release<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>This will call the method &#8220;methodToCall&#8221; passing in the object &#8220;objectToPassToMethod&#8221; in a separate thread.  Let&#8217;s see how this can be added to our code above to make it run smoother.</p>
<h4>The Solution</h4>
<p>Here we still have a method being fired when the user presses the &#8220;Load&#8221; button, but instead of fetching the data, this method fires off an NSOperation to fetch the data.  Check out the updated code.</p>
<h3><span style="color: #00ff00;">Correct (<span style="color: #00ff00;"><a href="/wp-content/uploads/2010/03/NSOperationTable11.zip"><span style="color: #00ff00;">Download the source code here</span></a></span>)</span></h3>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> RootViewController
<span style="color: #a61390;">@synthesize</span> array;
&nbsp;
<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>;
&nbsp;
    self.navigationItem.rightBarButtonItem <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIBarButtonItem alloc<span style="color: #002200;">&#93;</span> initWithTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Load&quot;</span>
       style<span style="color: #002200;">:</span>UIBarButtonItemStyleDone
       target<span style="color: #002200;">:</span>self
       action<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>loadData<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #400080;">NSMutableArray</span> <span style="color: #002200;">*</span>_array <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> initWithCapacity<span style="color: #002200;">:</span><span style="color: #2400d9;">10000</span><span style="color: #002200;">&#93;</span>;
    self.array <span style="color: #002200;">=</span> _array;
    <span style="color: #002200;">&#91;</span>_array release<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> loadData <span style="color: #002200;">&#123;</span>
&nbsp;
    <span style="color: #11740a; font-style: italic;">/* Operation Queue init (autorelease) */</span>
    <span style="color: #400080;">NSOperationQueue</span> <span style="color: #002200;">*</span>queue <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSOperationQueue</span> new<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">/* Create our NSInvocationOperation to call loadDataWithOperation, passing in nil */</span>
    <span style="color: #400080;">NSInvocationOperation</span> <span style="color: #002200;">*</span>operation <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSInvocationOperation</span> alloc<span style="color: #002200;">&#93;</span> initWithTarget<span style="color: #002200;">:</span>self
        selector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>loadDataWithOperation<span style="color: #002200;">&#41;</span>
        object<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;">/* Add the operation to the queue */</span>
    <span style="color: #002200;">&#91;</span>queue addOperation<span style="color: #002200;">:</span>operation<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>operation release<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> loadDataWithOperation <span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSURL</span> <span style="color: #002200;">*</span>dataURL <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/samples/nsoperation/data.plist&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>tmp_array <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithContentsOfURL<span style="color: #002200;">:</span>dataURL<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>str <span style="color: #a61390;">in</span> tmp_array<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>self.array addObject<span style="color: #002200;">:</span>str<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #002200;">&#91;</span>self.tableView performSelectorOnMainThread<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>reloadData<span style="color: #002200;">&#41;</span> withObject<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> waitUntilDone<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#pragma mark Table view methods</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: #002200;">&#91;</span>self.array count<span style="color: #002200;">&#93;</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>
&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;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>;
    <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>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> autorelease<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #002200;">&#91;</span>cell.textLabel setText<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self.array objectAtIndex<span style="color: #002200;">:</span>indexPath.row<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">return</span> cell;
<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>dealloc <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>array release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>As you can see, we haven&#8217;t added much code here, but we have GREATLY improved the overall user experience.  So, what did I do exactly?</p>
<ol>
<li>Moved all of the processing (downloading) code from the loadData method to another method that could be run asynchronously</li>
<li>Created a new instance of NSOperationQueue by calling [NSOperationQueue new]</li>
<li>Created an NSInvocationOperation to call our method loadDataWithOperation</li>
<li>Added the operation to the queue</li>
<li>Released the operation</li>
<li>When the Data has been downloaded, we reload the table data in the main thread since it&#8217;s a UI manipulation</li>
</ol>
<p>One thing to note here is we never actually tell the operation to run.  This is handled automatically in the queue.   The queue will figure out the optimal time run the operation and do it for you.</p>
<p>Now that you have your downloading and processing in a separate thread, you are now free to add things such as a loading view.</p>
<p>I will be expanding on this tutorial in the coming week and showing you how to cache data and display old data to the user while the new is loading.  This is a popular technique used in many Twitter and News applications.</p>
<p>That concludes today&#8217;s tutorial.</p>
<p>Post questions in the comments or <a href="http://twitter.com/brandontreb">Ping me on Twitter</a>.</p>
<p>Happy iCoding!</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2010/03/04/iphone-coding-turbo-charging-your-apps-with-nsoperation/feed/</wfw:commentRss>
		<slash:comments>65</slash:comments>
		</item>
		<item>
		<title>iPhone Coding Snippet &#8211; Shortening URLs</title>
		<link>http://icodeblog.com/2010/02/04/iphone-coding-recipe-shortening-urls/</link>
		<comments>http://icodeblog.com/2010/02/04/iphone-coding-recipe-shortening-urls/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 21:42:35 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Snippets]]></category>
		<category><![CDATA[iPhone Coding]]></category>
		<category><![CDATA[tr.im api]]></category>
		<category><![CDATA[url shortening iphone]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=1756</guid>
		<description><![CDATA[I had some a to shorten URLs for an in-application Twitter client I'm working on and thought I would share my simple solution with you guys.

It's actually pretty straight forward and can be done in 1 line of code.  I have broken it up into several for clarity.]]></description>
				<content:encoded><![CDATA[<p>I had some a to shorten URLs for an in-application Twitter client I&#8217;m working on and thought I would share my simple solution with you guys.</p>
<p>It&#8217;s actually pretty straight forward and can be done in 1 line of code.  I have broken it up into several for clarity.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>url    <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://brandontreb.com&quot;</span>;
<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>apiEndpoint <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://api.tr.im/v1/trim_simple?url=%@&quot;</span>,url<span style="color: #002200;">&#93;</span>;
<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>shortURL <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithContentsOfURL<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> URLWithString<span style="color: #002200;">:</span>apiEndpoint<span style="color: #002200;">&#93;</span>
		 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>;
NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Long: %@ - Short: %@&quot;</span>,url,shortURL<span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Outputs Long: http://brandontreb.com - Short: http://tr.im/MRDd</span></pre></td></tr></table></div>

<p>Pretty easy huh?</p>
<p>The magic here is in a method that Apple gave us as part of NSString.  This method is called stringWithContentsOfURL.  It will easily allow you to grab the text of any remote source.</p>
<p>I have used Tr.im as an example here because their service is very easy to use and has little overhead.  I would have used bit.ly but they return a JSON string which would then have to be parsed.  Tr.im&#8217;s trim_simple service simply outputs the string of the shortened URL.</p>
<p>Sure Twitter may shorten links for you automatically, but what if you want to use a custom service? Or,&#8230;wait for it&#8230; use it for something other than Twitter (please post in the comments if you do. I would love to hear some other uses :))</p>
<p>Questions? Comments? Complaints?</p>
<p>Happy iCoding</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2010/02/04/iphone-coding-recipe-shortening-urls/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>UITextField &#8211; A Complete API Overview</title>
		<link>http://icodeblog.com/2010/01/04/uitextfield-a-complete-api-overview/</link>
		<comments>http://icodeblog.com/2010/01/04/uitextfield-a-complete-api-overview/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 17:58:18 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[iPhone Coding]]></category>
		<category><![CDATA[iphone programming]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[UITextField]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=1547</guid>
		<description><![CDATA[The UITextField is probably one of the most commonly used UI controls on the iPhone. It is the primary method of user input via the keyboard and provides a great deal of additional functionality.
With the success of our las API tutorial on <a href="/2009/08/26/objective-c-tutorial-nsarray/">NSArray</a>, I thought I would do another walkthrough, this time on UITextField. I will be explaining all of the properties for it as well as bringing up some functionality that you may not have known about.
Text Attributes
The  ...]]></description>
				<content:encoded><![CDATA[<p style="clear: both;">The UITextField is probably one of the most commonly used UI controls on the iPhone. It is the primary method of user input via the keyboard and provides a great deal of additional functionality.</p>
<p>With the success of our las API tutorial on <a href="/2009/08/26/objective-c-tutorial-nsarray/">NSArray</a>, I thought I would do another walkthrough, this time on UITextField. I will be explaining all of the properties for it as well as bringing up some functionality that you may not have known about.</p>
<h2>Text Attributes</h2>
<p style="clear: both;">The attributes have to do with the actual text inside of the UITextField.<br />
<style type="text/css"> table.api td {border:1px solid #777;} </style>
</p>
<table class="api" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>text</td>
<td>The text displayed in the UITextField</td>
</tr>
<tr>
<td>placeholder</td>
<td>The text that gets displayed prior to the user entering in anything. This text is usually a lighter color than the primary text to denote that it will be replaced.</td>
</tr>
<tr>
<td>font</td>
<td>The font of the text to be displayed. You can set it like this</td>
</tr>
<tr>
<td>textColor</td>
<td>The color of the text that is displayed</td>
</tr>
<tr>
<td>textAlignment</td>
<td>How the text is aligned in the UITextField. The possible values for this are UITextAlignmentLeft, UITextAlignmentRight, UITextAlignmentCenter</td>
</tr>
</tbody>
</table>
<p style="clear: both;">
<p style="clear: both;">Here are some examples of using these properties.</p>
<p style="clear: both;">

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Setting the text</span>
<span style="color: #002200;">&#91;</span>myTextField setText<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;This is some text!&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Setting the placeholder</span>
<span style="color: #002200;">&#91;</span>myTextField setPlaceholder<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Type text here&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Setting the font.</span>
<span style="color: #002200;">&#91;</span>myTextField setFont<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>UIFont fontWithName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Times New Roman&quot;</span> size<span style="color: #002200;">:</span><span style="color: #2400d9;">14</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Setting the text color</span>
<span style="color: #002200;">&#91;</span>myTextField setTextColor<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>UIColor blueColor<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Setting the text alignment</span>
<span style="color: #002200;">&#91;</span>myTextField setTextAlignment<span style="color: #002200;">:</span>UITextAlignmentCenter<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p style="clear: both;">
<p style="clear: both;"><img class="alignnone size-full wp-image-1570" style="display: inline; float: left; margin: 0 10px 10px 0;" src="/wp-content/uploads/2009/12/screenshot_011.png" alt="" width="298" height="50" align="left" />Here is what the UITextField would look like after we update these properties.</p>
<p style="clear: both;"><img class="alignnone size-full wp-image-1571" style="display: inline; float: left; margin: 0 10px 10px 0;" title="screenshot_02" src="/wp-content/uploads/2009/12/screenshot_021.png" alt="" width="298" height="52" align="left" /><br style="clear: both;" /></p>
<h2>Adjusting the size of the text in the UITextField</h2>
<p style="clear: both;">
<p style="clear: both;">
<p style="clear: both;">The text displayed in our UITextField can be dynamically sized based on the width of the UITextField. The benefit of this is all of the text being typed will be visible on the screen. It will shrink the text down until it reaches the default font size of 17. So, for this to make sense, you must set the font size of the UITextField to something larger than 17.</p>
<table class="api" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>adjustsFontSizeToFitWidth</td>
<td>Boolean value denoting whether to fit the font size to the width of the UITextField.</td>
</tr>
</tbody>
</table>
<p style="clear: both;">
<p style="clear: both;">Here is an example of using these properties.</p>
<p style="clear: both;">

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>myTextField setFont<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>UIFont fontWithName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Times New Roman&quot;</span> size<span style="color: #002200;">:</span><span style="color: #2400d9;">30</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>myTextField setAdjustsFontSizeToFitWidth<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p style="clear: both;">
<p style="clear: both;"><img class="alignnone size-full wp-image-1577" style="display: inline; float: left; margin: 0 10px 10px 0;" title="screenshot_03" src="/wp-content/uploads/2009/12/screenshot_031.png" alt="" width="298" height="55"  />Here are some screenshots of the text shrinking when typing in the UITextField.</p>
<p style="clear: both;"><img class="alignnone size-full wp-image-1578" style="display: inline; float: left; margin: 0 10px 10px 0;" title="screenshot_04" src="/wp-content/uploads/2009/12/screenshot_041.png" alt="" width="298" height="48" /></p>
<p style="clear: both;"><img class="alignnone size-full wp-image-1579" style="display: inline; float: left; margin: 0 10px 10px 0;" title="screenshot_05" src="/wp-content/uploads/2009/12/screenshot_051.png" alt="" width="298" height="52"  /><br style="clear: both;" /></p>
<h2>Managing the editor&#8217;s behavior</h2>
<p style="clear: both;">
<p style="clear: both;">
<p style="clear: both;">These two properties are pretty straight forward.</p>
<table class="api" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>editing</td>
<td>Read-only boolean value letting you know if the user is currently editing the UITextField</td>
</tr>
<tr>
<td>clearsOnBeginEditing</td>
<td>Clears the text in the field every time the user begins to edit it.</td>
</tr>
</tbody>
</table>
<p style="clear: both;">
<p style="clear: both;">Not very exciting and probably doesn&#8217;t even deserve an example&#8230;</p>
<p style="clear: both;">
<p style="clear: both;">
<p style="clear: both;">
<h2>Setting the view&#8217;s background appearance</h2>
<p style="clear: both;">
<p style="clear: both;">
<p style="clear: both;">This group of properties defines how the UITextField will look. If you have ever seen a fancy input box, this is how they are doing it.</p>
<table  class="api" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>borderStyle</td>
<td>Defines the type of border for the UITextField. Possible choices are UITextBorderStyleNone, UITextBorderStyleLine, UITextBorderStyleBezel, and UITextBorderStyleRoundedRect. The default is UITextBorderStyleNone.</td>
</tr>
<tr>
<td>background</td>
<td>A UIImage representing the background image of the UITextField when it&#8217;s enabled. If this field is altered the borderStyle property is ignored.</td>
</tr>
<tr>
<td>backgroundDisabled</td>
<td>A UIImage representing the background image of the UITextField when it&#8217;s disabled.</td>
</tr>
</tbody>
</table>
<p style="clear: both;">
<p style="clear: both;">Here is are some example of using each of the border styles</p>
<p style="clear: both;">

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Border Style None</span>
<span style="color: #002200;">&#91;</span>myTextField setBorderStyle<span style="color: #002200;">:</span>UITextBorderStyleNone<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p style="clear: both;">
<p style="clear: both;"><img class="alignnone size-full wp-image-1635" style="display: inline; float: left; margin: 0 10px 10px 0;" title="screenshot_05" src="/wp-content/uploads/2010/01/screenshot_051.png" alt="" width="290" height="43" align="left" /></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Border Style Line</span>
<span style="color: #002200;">&#91;</span>myTextField setBorderStyle<span style="color: #002200;">:</span>UITextBorderStyleLine<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p style="clear: both;">
<p style="clear: both;"><img class="alignnone size-full wp-image-1637" style="display: inline; float: left; margin: 0 10px 10px 0;" title="screenshot_03" src="/wp-content/uploads/2010/01/screenshot_031.png" alt="" width="288" height="41" align="left" /></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Border Style Bezel</span>
<span style="color: #002200;">&#91;</span>myTextField setBorderStyle<span style="color: #002200;">:</span>UITextBorderStyleBezel<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p style="clear: both;">
<p style="clear: both;"><img class="alignnone size-full wp-image-1636" style="display: inline; float: left; margin: 0 10px 10px 0;" title="screenshot_02" src="/wp-content/uploads/2010/01/screenshot_022.png" alt="" width="291" height="42" align="left" /></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Border Style Rounded Rect</span>
<span style="color: #002200;">&#91;</span>myTextField setBorderStyle<span style="color: #002200;">:</span>UITextBorderStyleRoundedRect<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p style="clear: both;">
<p style="clear: both;"><a class="image-link" href="/wp-content/uploads/2010/01/screenshot_041.png"><img class="alignnone size-full wp-image-1638" style="display: inline; float: left; margin: 0 10px 10px 0;" title="screenshot_04" src="/wp-content/uploads/2010/01/screenshot_041.png" alt="" width="288" height="41" align="left" /></a></p>
<p style="clear: both;"><a class="image-link" href="/wp-content/uploads/2010/01/bg1.png"><img class="alignnone size-full wp-image-1641" style="display: inline; float: left; margin: 0 10px 10px 0;" title="bg" src="/wp-content/uploads/2010/01/bg1.png" alt="" width="185" height="28" align="left" /></a>The border style is not terribly exciting. However, you can really spruce up your UITextFields using the background property. Here is an example of setting the background property to this image.</p>
<p style="clear: both;">

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">myTextField.textAlignment <span style="color: #002200;">=</span> UITextAlignmentCenter;
myTextField.textColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIColor whiteColor<span style="color: #002200;">&#93;</span>;
myTextField.borderStyle <span style="color: #002200;">=</span> UITextBorderStyleNone;
myTextField.background <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIImage imageNamed<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bg.png&quot;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p style="clear: both;">
<p style="clear: both;"><img class="alignnone size-full wp-image-1642" style="display: inline; float: left; margin: 0 10px 10px 0;" title="screenshot_01" src="/wp-content/uploads/2010/01/screenshot_015.png" alt="" width="288" height="46" align="left" />and the result&#8230; Looks pretty good ehh? One GOTCHA that I want to point out here is, to get the background property to work correctly, you must set the boderStyle to anything other than UITextBorderStyleRoundedRect. Otherwise, the default UITextField will be displayed.<br />
Setting the view&#8217;s background appearance</p>
<p style="clear: both;">
<h2>Managing Overlay Views</h2>
<p>Another interesting way of customizing your UITextFields is to use an overlay. UITextField offers a left and right overlay for your UITextFields. Here are the properties:</p>
<table class="api" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>clearButtonMode</td>
<td>The circled X that gets displayed when typing. Used to clear out the text. Possible values: UITextFieldViewModeNever, UITextFieldViewModeWhileEditing, UITextFieldViewModeUnlessEditing, UITextFieldViewModeAlways</td>
</tr>
<tr>
<td>leftView</td>
<td>The view that appears to the left inside a UITextField. This could be something like a magnifying glass for search.</td>
</tr>
<tr>
<td>leftViewMode</td>
<td>Works like clearButtonMode, but toggles the leftView.</td>
</tr>
<tr>
<td>rightView</td>
<td>Same as leftView, except it aligns to the right.</td>
</tr>
<tr>
<td>rightViewMode</td>
<td>Same as leftViewMode but controls the rightView</td>
</tr>
</tbody>
</table>
<p>Let&#8217;s take a look at how adjusting the leftView works:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">UIImageView <span style="color: #002200;">*</span> myView <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span> UIImageView  alloc <span style="color: #002200;">&#93;</span>  initWithImage <span style="color: #002200;">:</span>
		<span style="color: #002200;">&#91;</span>UIImage  imageNamed <span style="color: #002200;">:</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;wordpress.png&quot;</span> <span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>myTextField  setLeftView <span style="color: #002200;">:</span>myView<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span> myTextField   setLeftViewMode<span style="color: #002200;">:</span> UITextFieldViewModeAlways<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>myView release <span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p><img class="alignnone size-full wp-image-1651" title="screenshot_01" src="/wp-content/uploads/2010/01/screenshot_0111.png" alt="" width="291" height="44" /></p>
<p>As you can see, the text aligns after the image.  This is a very simple way to really spruce up your UITextFields.</p>
<p>The last thing we are going to discuss is showing and hiding the keyboard.</p>
<h2>Showing and Hiding The Keyboard</h2>
<p>To show the keyboard:</p>

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

<p>To hide the keyboard</p>

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

<p>Well, I hope you have enjoyed this tutorial on the <strong>UITextField</strong>.  I would love to see links to some interesting custom UITextFields in the comments, so please post them.  Thanks for reading and happy iCoding!</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2010/01/04/uitextfield-a-complete-api-overview/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>iPhone Coding Tutorial &#8211; Creating an Online Leaderboard For Your Games</title>
		<link>http://icodeblog.com/2009/10/29/iphone-coding-tutorial-creating-an-online-leaderboard-for-your-games/</link>
		<comments>http://icodeblog.com/2009/10/29/iphone-coding-tutorial-creating-an-online-leaderboard-for-your-games/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 16:14:50 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[iPhone Coding]]></category>
		<category><![CDATA[iphone game]]></category>
		<category><![CDATA[leaderboard]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=1426</guid>
		<description><![CDATA[As you may have seen, there are quite a few services out there offering free leaderboards.  These are great and all, but sometimes you want to have complete control over your data.  I have put together a complete tutorial detailing step by step how you can create your own online leaderboard.  This will also give you a very simple introduction to interfacing with web services.]]></description>
				<content:encoded><![CDATA[<p>As you may have seen, there are quite a few services out there offering free leaderboards.  These are great and all, but sometimes you want to have complete control over your data.  I have put together a complete tutorial detailing step by step how you can create your own online leaderboard for use in your iPhone games.  For those of you who don&#8217;t know, a leaderboard is essentially a high scores list.  This tutorial will also give you a very simple introduction to interfacing with web services.</p>
<p>The first part of this tutorial will discuss how to build the server.  We will be doing this using PHP and MYSQL.  I will also assume you have some working knowledge of PHP and MYSQL (if not, use the Google machine to get up to speed).</p>
<p>Since this tutorial is so long, I have decided to split it up into pages.  You will notice the page number at the bottom.  Please use them to navigate between parts of this post.  I feel that I have to make this explicit as I will undoubtably get some dude in the comments saying &#8220;Where is the rest of the tutorial&#8221;.</p>
<p>Skill level: <font color="red">Advanced</font></p>
<h2>Creating The Database</h2>
<p>When creating a leaderboard, you will need some way of storing the data.  We will be using MYSQL for our storage.  You can also be lame and simply use flat files.  This would add quite a bit of code in the long run as you would have to write all of the sorting and pagination functionality yourself. Don&#8217;t do it.</p>
<p>One thing to note about my php server files.  I know they could be cleaned up a little and optimized (you could create a config.php that contains all the db interface code), but the goal of this tutorial is not to show you how to code killer PHP.  It&#8217;s to show you how to create code that you can connect your iPhone apps to.</p>
<p>I like to create one file that does a complete flash of the database.  That way, when I&#8217;m testing or switch from staging to production, it is a very simple process.  So, with that being said, here is my code for create_db.php.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
        <span style="color: #666666; font-style: italic;">// create_db.php</span>
	<span style="color: #009933; font-style: italic;">/** MySQL database name */</span>
	<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_NAME'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">''</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009933; font-style: italic;">/** MySQL database username */</span>
	<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_USER'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">''</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009933; font-style: italic;">/** MySQL database password */</span>
	<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_PASSWORD'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">''</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009933; font-style: italic;">/** MySQL hostname */</span>
	<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_HOST'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_ENV</span><span style="color: #009900;">&#123;</span>DATABASE_SERVER<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000088;">$table</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;highscores&quot;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Initialization</span>
	<span style="color: #000088;">$conn</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_connect</span><span style="color: #009900;">&#40;</span>DB_HOST<span style="color: #339933;">,</span>DB_USER<span style="color: #339933;">,</span>DB_PASSWORD<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #990000;">mysql_select_db</span><span style="color: #009900;">&#40;</span>DB_NAME<span style="color: #339933;">,</span> <span style="color: #000088;">$conn</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Error checking</span>
	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$conn</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #990000;">die</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Could not connect '</span> <span style="color: #339933;">.</span> <span style="color: #990000;">mysql_error</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Drop existing table if exists</span>
	<span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;DROP TABLE <span style="color: #006699; font-weight: bold;">$table</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$conn</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000088;">$retval</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;CREATE TABLE <span style="color: #006699; font-weight: bold;">$table</span>(
		id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
		udid VARCHAR(45),
		name VARCHAR(25),
		score FLOAT(10,2),
		date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
	)&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$conn</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$retval</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Database created...&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Could not create database &quot;</span> <span style="color: #339933;">.</span> <span style="color: #990000;">mysql_error</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #990000;">mysql_close</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$conn</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>I&#8217;m not going to go into too much detail about this code, however I will give a high level description of what&#8217;s going on.  One thing to note about this code is it assumes you already have the database created.</p>
<p>First, we are defining variables that contain our database information.  Make sure you replace my empty strings with your database info. After we connect to the database, we drop the table if it already exists.  This is useful if you want to wipe out your test data.  Finally, we create the scores table.  Navigate to this file in your browser to run it and create the scores table.  Pretty easy right?</p>
<p><font color="red">You will want to make sure to remove this file from your server after running it to avoid people resetting your database.</font></p>
<p>Now that our database table has been created, it&#8217;s time to implement the web service code to publish new scores to our leaderboard.</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2009/10/29/iphone-coding-tutorial-creating-an-online-leaderboard-for-your-games/feed/</wfw:commentRss>
		<slash:comments>48</slash:comments>
		</item>
		<item>
		<title>Debugging Tutorial &#8211; Automating Your Tests With A UIRecorder Instrument</title>
		<link>http://icodeblog.com/2009/10/06/debugging-tutorial-automating-your-tests-with-a-uirecorder-instrument/</link>
		<comments>http://icodeblog.com/2009/10/06/debugging-tutorial-automating-your-tests-with-a-uirecorder-instrument/#comments</comments>
		<pubDate>Tue, 06 Oct 2009 21:20:00 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Advanced]]></category>
		<category><![CDATA[iPhone Coding]]></category>
		<category><![CDATA[iphone debugging]]></category>
		<category><![CDATA[uirecorder]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=1403</guid>
		<description><![CDATA[If you have ever experienced a bug in your application that took many steps to reproduce, then this tutorial is for you.  By nature, testing and debugging are very tedious processes.  This is especially the case for the iPhone.
Say you have an app that drills down 5-levels deep to some other view.  Now let&#8217;s say that you have a bug on that view 5 levels deep.  Your normal method of debugging is:

Run the app
Tap view 1
Tap  ...]]></description>
				<content:encoded><![CDATA[<p>If you have ever experienced a bug in your application that took many steps to reproduce, then this tutorial is for you.  By nature, testing and debugging are very tedious processes.  This is especially the case for the iPhone.</p>
<p>Say you have an app that drills down 5-levels deep to some other view.  Now let&#8217;s say that you have a bug on that view 5 levels deep.  Your normal method of debugging is:</p>
<ul>
<li>Run the app</li>
<li>Tap view 1</li>
<li>Tap view 2</li>
<li>Tap view 3</li>
<li>Tap view 4</li>
<li>Tap view 5</li>
<li>(Crash)</li>
<li>Change some code</li>
<li>Repeat</li>
</ul>
<p>As you can see (and I&#8217;m sure have noticed), this sucks.  Well, <a href="http://twitter.com/kendalldevdiary">Kendall Gelner</a> gave a killer talk at <a href="http://www.360idev.com/">360iDev</a> (which I recently attended) on various debugging tips using Instruments and XCode.  One of the most useful techniques (to me) was how to automate your testing.  Let me show you what I mean.</p>
<p>1. Open up the app you wish to test/debug</p>
<p>2. Launch it in the simulator</p>
<p>3. Open <strong>Instruments</strong> &#8211; This is located in /Developer/Applications/Instruments (just do a spotlight search for it)</p>
<p><strong><a href="/wp-content/uploads/2009/10/screenshot_012.png"><img class="alignnone size-medium wp-image-1404" title="screenshot_01" src="/wp-content/uploads/2009/10/screenshot_01-300x229.png" alt="screenshot_01" width="300" height="229" /></a></strong></p>
<p>4. Select <strong>UIRecorder</strong> and click <strong>Choose </strong>- You should now see a window like this</p>
<p><strong><a href="/wp-content/uploads/2009/10/screenshot_021.png"><img class="alignnone size-medium wp-image-1406" title="screenshot_02" src="/wp-content/uploads/2009/10/screenshot_02-300x211.png" alt="screenshot_02" width="300" height="211" /></a></strong></p>
<p>5. Now, we need to attach this tool to the iPhone Simulator process.  Click the drop-down above <strong>Default Target</strong> -&gt; <strong>Attach to Process </strong>-&gt; <strong>iPhone Simulator</strong>.</p>
<p><a href="/wp-content/uploads/2009/10/ss_031.png"><img class="alignnone size-medium wp-image-1409" title="ss_03" src="/wp-content/uploads/2009/10/ss_03-300x136.png" alt="ss_03" width="300" height="136" /></a></p>
<p>6. Now click <strong>Drive &amp; Record</strong> and do all of the steps in the simulator to test your app.  At this point, the UI Recorder is recording your every move.  When you have finished press the <strong>Stop </strong>button. <span style="color: #ff0000;">Note</span>: After you have recorded your actions, don&#8217;t move the simulator as it will mess up the entire process.</p>
<p>7. Modify your code&#8230;</p>
<p>8. Press the <strong>Drive &amp; Record </strong>button and watch the magic happen.  The test is automatically done for you.  You should see your mouse move over to the simulator and the system mimicking every action that you did before.</p>
<p>That&#8217;s it! I know this isn&#8217;t a super long tutorial (or even a coding tutorial), but the UI Recorder has sped my test time up tremendously.  Give it a shot and let me know what you think.  Here is a short video of me going through all of the steps.</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="400" height="300" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://vimeo.com/moogaloop.swf?clip_id=6934052&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed type="application/x-shockwave-flash" width="400" height="300" src="http://vimeo.com/moogaloop.swf?clip_id=6934052&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p><a href="http://vimeo.com/6934052">iCodeBlog &#8211; Debugging Tutorial &#8211; Automating Your Tests With A UIRecorder Instrument</a> from <a href="http://vimeo.com/user2413855">Brandon Trebitowski</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
<p>Happy iCoding!</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2009/10/06/debugging-tutorial-automating-your-tests-with-a-uirecorder-instrument/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Code Snippet &#8211; Quickly Find The Documents Directory</title>
		<link>http://icodeblog.com/2009/09/09/code-snippet-quickly-find-the-documents-directory/</link>
		<comments>http://icodeblog.com/2009/09/09/code-snippet-quickly-find-the-documents-directory/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 14:54:18 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Snippets]]></category>
		<category><![CDATA[iPhone Coding]]></category>
		<category><![CDATA[iphone dev]]></category>
		<category><![CDATA[iphone documents]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[save files]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=1295</guid>
		<description><![CDATA[As many of you may have seen by now, there are quite a few ways to find the documents directory on the iPhone.  For those of you who don&#8217;t know, the documents directory of an app is the location where you should save your application data.  While finding the documents directory is a trivial task, it is very important when coding most applications.  Apple has provided quite a few ways for resolving the path to this directory.
If  ...]]></description>
				<content:encoded><![CDATA[<p>As many of you may have seen by now, there are quite a few ways to find the documents directory on the iPhone.  For those of you who don&#8217;t know, the documents directory of an app is the location where you should save your application data.  While finding the documents directory is a trivial task, it is very important when coding most applications.  Apple has provided quite a few ways for resolving the path to this directory.</p>
<p>If you read through some of Apple&#8217;s sample code, you will see their code to do this is generally 3 or 4 lines long.  This seems like a lot of code to perform such a simple task.  Here is a nice one-liner for you to use in your applications.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span> docs <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>NSHomeDirectory<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>
						   stringByAppendingPathComponent<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Documents&quot;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>It&#8217;s clean and concise.  Happy iCoding!</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2009/09/09/code-snippet-quickly-find-the-documents-directory/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Objective-C Tutorial: NSArray</title>
		<link>http://icodeblog.com/2009/08/26/objective-c-tutorial-nsarray/</link>
		<comments>http://icodeblog.com/2009/08/26/objective-c-tutorial-nsarray/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 19:04:46 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[iPhone Coding]]></category>
		<category><![CDATA[iphone dev]]></category>
		<category><![CDATA[nsarray]]></category>
		<category><![CDATA[NSMutableArray]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=1268</guid>
		<description><![CDATA[The NSArray is a huge workhorse that we use quite frequently without even thinking about it.  The NSArray class isn't just your ordinary array.  Not only does it provide random access, but it also dynamically re-sizes when you add new objects to it.  While I won't go over every method in NSArray (there are quite a few), I will discuss some of the more important ones that are most commonly used.  Let's take a closer look at this class.]]></description>
				<content:encoded><![CDATA[<p>Here at iCodeblog, we have been showing you guys how to create many different types of applications from the ground up.  Well, today I decided to do something different and get down to some of the nitty gritty of a structure we rely heavily on in objective-C.</p>
<p>The NSArray is a huge workhorse that we use quite frequently without even thinking about it.  The NSArray class isn&#8217;t just your ordinary array.  Not only does it provide random access, but it also dynamically re-sizes when you add new objects to it and has many methods to make our lives easier.  While I won&#8217;t go over every method in NSArray (there are quite a few), I will discuss some of the more important ones that are most commonly used.  Let&#8217;s take a closer look at this class.</p>
<h2>Factory Methods</h2>
<p>Factory methods are <a href="http://en.wikipedia.org/wiki/Static_method#Static_methods">static methods</a> that build new instances of NSArrays from given parameters and return them.  The table below details on all of the factory methods for the NSArray class.</p>
<table style="border: 1px solid #000000; width: 100%;" border="0">
<tbody>
<tr>
<td><strong>+ (id)array</strong></td>
<td>Creates and returns an empty array</td>
</tr>
<tr>
<td><strong>+ (id)arrayWithArray:(NSArray *)anArray</strong></td>
<td>Creates and returns an array containing the objects in another given array.</td>
</tr>
<tr>
<td><strong>+ (id)arrayWithContentsOfFile:(NSString *)aPath</strong></td>
<td>Creates and returns an array containing the contents of the file specified by a given path. <span style="color: red;">*</span> The file must be of type .plist for this method to work</td>
</tr>
<tr>
<td><strong>+ (id)arrayWithContentsOfURL:(NSURL *)aURL</strong></td>
<td>Similar to arrayWithContentsOfFile except it will load the .plist remotely from a given website.  This would be a very simple way to get data from a web service.</td>
</tr>
<tr>
<td><strong>+ (id)arrayWithObject:(id)anObject</strong></td>
<td>Creates and returns an array containing a given object.  This will just be a 1 element array</td>
</tr>
<tr>
<td><strong>+ (id)arrayWithObjects:(id)firstObj, &#8230;</strong></td>
<td>This method is used when you have multiple objects on hand and want easily insert them into an array.  Make sure the last element you add is nil or this method won&#8217;t work.</td>
</tr>
<tr>
<td><strong>+ (id)arrayWithObjects:(const id *)objects count:(NSUInteger)count</strong></td>
<td>Creates and returns an array that includes a given number of objects from a given C array.</td>
</tr>
</tbody>
</table>
<p>Here is some example usage of building NSArrays with these factory methods&#8230;</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// I am using strings, but you can add just about any object to an NSArray</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// Creates an NSArray with one object</span>
<span style="color: #400080;">NSArray</span>  <span style="color: #002200;">*</span> myArray <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: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;foo&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Creates an NSArray with multiple objects. Don't forget to add nil as the last object</span>
<span style="color: #400080;">NSArray</span>  <span style="color: #002200;">*</span> myArray2 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithObjects<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;foo&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bar&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;baz&quot;</span>,<span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Creates an NSArray from another NSArray</span>
<span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span> myArray3 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithArray<span style="color: #002200;">:</span>myArray2<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// This will create an NSArray from data on iCodeBlog.  Go ahead and try it out, this file exists on our servers and contains valid data.</span>
<span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span> myArray4 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithContentsOfURL<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/2009/08/foo.plist&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>You can also choose not to use factory methods and just use the normal NSArray initializers.  They are pretty much the same as the factory methods only you do the allocation yourself. An example of this might be:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span> foo <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> alloc<span style="color: #002200;">&#93;</span> initWithObjects<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;foo&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bar&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;baz&quot;</span>,<span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<h2>Accessing The NSArray</h2>
<p>Apple has provided us with many great methods for getting data out of an NSArray as well as information about it.  Here is a table of methods and their descriptions.</p>
<table style="border: 1px solid #000000; width: 100%;" border="0">
<tbody>
<tr>
<td>- (BOOL)containsObject:(id)anObject</td>
<td>Returns true if a given object is found in the array, false otherwise</td>
</tr>
<tr>
<td>- (NSUInteger)count</td>
<td>Returns the size of the array</td>
</tr>
<tr>
<td>- (id)lastObject</td>
<td>Returns the last object in the array (the one with the highest index)</td>
</tr>
<tr>
<td>- (id)objectAtIndex:(NSUInteger)index</td>
<td>Gives you random access to the array. Returns the object at a given index.</td>
</tr>
</tbody>
</table>
<p>These are just a few of the accessor methods of NSArray and most likely the only ones you will need to use.</p>
<h2>Searching The Array</h2>
<p>If you are looking for the index of an object in an array, there is really only one method you need to use.  That method is indexOfObject: . An example of usage might be:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span> f <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;foo&quot;</span>;
<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span> b <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bar&quot;</span>;
<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span> z <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;baz&quot;</span>;
<span style="color: #400080;">NSArray</span>  <span style="color: #002200;">*</span> myArray2 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithObjects<span style="color: #002200;">:</span>f,b,z,<span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
NSInteger idx <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>myArray2 indexOfObject<span style="color: #002200;">:</span>b<span style="color: #002200;">&#93;</span>;
<span style="color: #11740a; font-style: italic;">// This would return 1 (since NSArrays are 0 - indexed)</span></pre></td></tr></table></div>

<p>This is much cleaner code than looping over the entire array to find an object. It&#8217;s probably more efficient too as Apple is pretty clean in how they code things.</p>
<h2>Sending Message To Objects In The Array</h2>
<p>Ok, so this is pretty cool.  Say you have an array of objects that all need to do something.  For example, an array of bullets, and you want all of the bullets to move forward one pixel. Rather than looping over each bullet object in the bullets array and calling [bullet move], you can do it in one method call on the array.  This method is called &#8211; (void)makeObjectsPerformSelector:(SEL)aSelector and here is an example of usage.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Lets pretend the bullet object has a method called move</span>
<span style="color: #11740a; font-style: italic;">// and there is an array of 50 bullets</span>
&nbsp;
<span style="color: #002200;">&#91;</span>bullets makeObjectsPerformSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>move<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>And that&#8217;s it&#8230; The move method will now be called on every bullet object in the array with this one method call.  Very clean and easy to use.  Now, if the method you want to call takes an argument, there is the &#8211; (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)anObject method.  This will allow you to pass an object to each method being called.</p>
<h2>Sorting Arrays</h2>
<p>Apple has provided us with some very slick ways to sort an NSArray.  I will not go into too much detail here as I have a full tutorial planned dedicated to sorting arrays.  For now, I will just show you how to sort an NSArray of NSStrings.  The method we will be using is sortedArrayUsingSelector.  Here is the example usage.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>sortedArray <span style="color: #002200;">=</span>
    <span style="color: #002200;">&#91;</span>myArray2 sortedArrayUsingSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>caseInsensitiveCompare<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #11740a; font-style: italic;">// This will return a sorted array that looks like [@&quot;bar&quot;,@&quot;baz&quot;,@&quot;foo&quot;]</span></pre></td></tr></table></div>

<p>You can plug in any of the string compare functions there to compare the strings.  If you are sorting an NSArray of custom objects (like users), you can overwrite the compare method for that object and pass compare in for the selector.  Just make sure you remember the : at the end of the method.</p>
<h2>Looping Through Arrays</h2>
<p>So if you are reading this, I assume you have seen a for loop before.  ex: for(int x=0; x &lt; &#8230; This would most likely not be a good way to enumerate an NSArray as Apple has provided a much nice way for doing so.  There are some situations where this method would be preferred (like when u need to calculate the indices or something).  But in most cases, you will want to use the special for loop provided by Apple. If you have ever coded PHP, it is much like the foreach loop.  Here is an example:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">for</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span> myStr <span style="color: #a61390;">in</span> myArray2<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    NSLog<span style="color: #002200;">&#40;</span>myStr<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This will loop over myArray2 and pring each element in that array.  Very clean and efficient.</p>
<h2>Saving Arrays For Later</h2>
<p>There is an Array of ways to save data on the iPhone (Pun intended).  One way is to simply dump the array to a file.  This will write out the NSArray to a plist file on disk that can be loaded later using the arrayWithContentsOfFile method of NSArray.  That method is rightfully named writeToFile.  The example usage for it is as follows.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSArray</span>  <span style="color: #002200;">*</span> myArray2 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithObjects<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;foo&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bar&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;baz&quot;</span>,<span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>myArray2 writeToFile<span style="color: #002200;">:</span>filePath atomically<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>And there you have it! You are probably wondering what the atomically variable means. Me too&#8230; Just kidding.  If YES, the file will be written to a temp location and then renamed to its final destination.  This is put in place to guarantee that the file won&#8217;t be corrupted even if the system crashes (rename will be much faster than write).  Why is this needed you ask?  Consider this scenario.</p>
<blockquote><p>You want to write a huge array to disk to save it for later.  When your app starts it checks the disk to see if this file exists, if it does it loads an NSArray from it.  If it doesn&#8217;t it creates a new NSArray.  Say the last time the app ran, the system crashed while the file was being written.  If atomically was set to NO, the original file would be corrupt and now the application would be loading corrupt data every time it starts from now on (most likely causing a crash).  However, if you set atomically to YES, the temp file would get corrupted and the app would never see it.  That way, the next time the app starts it will create a new fresh NSArray and all will be good.</p></blockquote>
<p>Good rule of thumb, set atomically to YES.</p>
<p>That concludes our tutorial on NSArray.  If you have any questions or comments, feel free to post them in the comments section or <a href="http://twitter.com/brandontreb">write me on twitter.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2009/08/26/objective-c-tutorial-nsarray/feed/</wfw:commentRss>
		<slash:comments>44</slash:comments>
		</item>
	</channel>
</rss>
