<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Use Your Loaf</title>
    <link>http://useyourloaf.com</link>
    <atom:link href="http://useyourloaf.com/blog/rss.xml" rel="self" type="application/rss+xml"/>
    <description>Developing for the Apple iPhone and iOS.</description>
    <copyright>Copyright 2012 Keith Harrison</copyright>
    <language>en-GB</language>
    <lastBuildDate>Sat, 26 May 2012 17:09:00 +0100</lastBuildDate>
    <generator>Octopress</generator>
    
    <item>
		  <title>Making Some Changes</title>
		  <link>http://useyourloaf.com/blog/2012/05/25/making-some-changes.html</link>
      <pubDate>Fri, 25 May 2012 16:22:00 +0100</pubDate>
		  <guid>http://useyourloaf.com/blog/2012/05/25/making-some-changes.html</guid>
      
        <category>blog</category>
      
      <description><![CDATA[<p>If you are reading this post then it means some changes to this blog that I have been working on this week have gone live. If you subscribe to the RSS feed this probably also means that you have just seen the last ten posts show up again in your RSS reader. My apologies for that but I hope the end result is worth the temporary disturbance.</p>

<h3>Ancient History</h3>

<p>For more than two years this blog has been hosted on <a href="http://squarespace.com">SquareSpace.com</a> and for the most part I have been very happy with the service. If you are looking for a quick, easy and relatively cheap way to get a blog up and running it is an option well worth considering.</p>

<p>However I think it is time to make some changes to get the site closer to the way I want it. What follows is a brief description of what I have been up to this week.</p>

<h3>Static Blog using Octopress</h3>

<p>This is a very simple blog with very simple requirements so I have for a while been wanting to move to a static blog engine rather than a complex content management system such as SquareSpace or WordPress. With a static blog all of the content can be checked into a version control repository of my choosing allowing me complete freedom on how and where I host the site.</p>

<p>There are many static blog engines to choose from but I chose to use <a href="http://octopress.org">Octopress</a> a framework developed by <a href="http://brandonmathis.com/">Brandon Mathis</a> for <a href="http://github.com/mojombo/jekyll">Jekyll</a>. It already has plugins for everything that I could possibly want, works well in both desktop and mobile browsers and I figured that if it is good enough for <a href="http://mattgemmell.com/2011/09/12/blogging-with-octopress/">Matt Gemmell</a> it is surely good enough for me.</p>

<p>I will spare you the details of the migration as it mostly involved cleaning up the html export of my SquareSpace blog. The biggest pain was in fixing the URL&#8217;s of some posts and converting everything back to markdown format. I also had to convert the comments to the Wordpress XML comment format so that I could import them to Disqus. If you are really interested I posted the ruby script I used to convert both the posts and the comments in this <a href="https://gist.github.com/2783345">Gist</a>.</p>

<h3>Disqus Comments</h3>

<p>Early on I had a lot of problems with comment spam on squarespace but the comment moderation seems to have improved a lot lately. The iOS App also makes it easy to manage comments even though it seems to crash way too frequently. However with the move to a static blog I needed to reconsider what to do about comments.</p>

<p>It seems a lot of sites are now just disabling comments on the grounds that they are a pain to manage and often do not add any value. I really appreciate the feedback and suggestions I get in the comments on this site so I have decided to move them to <a href="http://disqus.com">Disqus</a>.</p>

<p>You do not currently need to have a Disqus account to leave a comment but I may change that setting in the future if Spam becomes a problem. You do need to specify an email address when posting but it is never displayed. Also note that to access the comment thread from the blog home page you need to first click on the individual blog post.</p>

<h3>Linode</h3>

<p>The final change this week has been to move the blog to a <a href="http://www.linode.com/?r=b33a255648781feb4512e8cb377d00d2081b7d5a">Linode (referral link)</a> hosted VPS and set up the web server. A static blog has no need for a backend database and does not need PHP, ruby, perl or any other means to generate dynamic content. As a result I opted for the smallest VPS node that Linode offers at a price that is comparable to what I was paying for the Squarespace site.</p>

<h3>Summary</h3>

<p>It is early days to say how well the migration has gone but so far I think it is a big improvement over the previous site. For me the extra administration involved in managing the whole site is a price worth paying but I guess you do need to be comfortable with some basic sys admin to make it work. So far I am pretty happy with the results. As always feedback and suggestions are welcome.</p>
]]></description>
    </item>
    
    <item>
		  <title>Detecting VoiceOver Status Changes</title>
		  <link>http://useyourloaf.com/blog/2012/05/14/detecting-voiceover-status-changes.html</link>
      <pubDate>Mon, 14 May 2012 20:26:00 +0100</pubDate>
		  <guid>http://useyourloaf.com/blog/2012/05/14/detecting-voiceover-status-changes.html</guid>
      
        <category>accessibility</category>
      
      <description><![CDATA[<p><em>This is a follow up to my recent post about adding <a href="http://useyourloaf.com/blog/2012/04/23/voiceover-accessibility.html">VoiceOver Accessibility</a> support to an iOS app to cover situations where you need to adjust the user interface when VoiceOver is active.</em></p>

<h3>Gestures and Accessibility</h3>

<p>I generally dislike Apps that rely exclusively on gestures such as touches, swipes or shaking the device to perform an operation. The gestures may well have been obvious to the developer but as a user I often struggle to discover what I am supposed to do. This leads to a situation where you end up randomly touching, pinching and swiping the screen to discover &#8220;hidden&#8221; features. This not only leads to a poor user experience but also presents real challenges to accessibility as the gestures are generally not available when VoiceOver is active.</p>

<p>I like to think of gestures as being the equivalent of a keyboard shortcut for a desktop application. The keyboard shortcut allows power users to perform an operation more efficiently but a toolbar icon or menu option allows a normal user to discover and perform the same operation. Likewise if an app makes use of a gesture it should generally have some visible on-screen control that can be used to perform the same operation. A good example is the common iOS gesture of swiping to delete a row in a table. If you are not aware of the gesture you can still use the edit button in the toolbar and then use the on-screen controls to delete rows. This also removes any issues with VoiceOver as long as you set the accessibility attributes for the on-screen controls.</p>

<p>Relying on a gesture as the only way to access a feature not only makes your app difficult to use with VoiceOver it also makes your app difficult to use for all users. Having said that if you have a situation where you really do not want to have an on-screen control you should at least consider modifying the user interface of the app when VoiceOver is active.</p>

<p>Another example that can cause accessibility issues can occur when you are displaying some information for a limited period of time. For example you might keep some details about a download on-screen for a few seconds after it completes. Using VoiceOver those few seconds might not be enough time for the user to navigate to, select and have VoiceOver read the label. In both cases we need to be able to detect VoiceOver status and change the behaviour and maybe even the user interface when it is active.</p>

<h3>Revisiting the Task Timer</h3>

<p>I previously created a simple task management app to show the basic techniques involved in adding VoiceOver support. The full details are contained in this <a href="http://useyourloaf.com/blog/2012/04/23/voiceover-accessibility.html">previous post</a> but the basic idea was to allow the user to create tasks and then time how long they took to complete. I am going to add a new feature to the app which will allow us to reset the duration of a task by shaking the device. This is just the sort of bad user interface design that I was referring to earlier but one which I hope will illustrate the idea.</p>

<p>Before we take a look at detecting whether VoiceOver is active we need to go on a small diversion to implement the shake to reset feature. Luckily this turns out to be trivial. When a user shakes a device the accelerometer generates motion events. The motion events can be received by any subclass of UIResponder but we need to make sure that our view controller can become the first responder:</p>

<pre><code>- (BOOL)canBecomeFirstResponder
{
  return YES;
}
</code></pre>

<p>We do not care in which direction the device is shaken so to detect the shake we implement motionEnded:withEvent: in the task view controller:</p>

<pre><code>- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
  [self taskResetAction];
}
</code></pre>

<p>I will not bother showing the details of the taskResetAction here as it is not relevant to this discussion. You can check the code if you are interested. Note that there is no way to test device shaking in the simulator so you will need to deploy to an actual device if you want to verify that the shake event actually works. The shake action will still work even if VoiceOver is activated but to improve the accessibility of the app we will look at how we can provide an alternative user interface when we detect VoiceOver is in use.</p>

<h3>Checking the Status of VoiceOver</h3>

<p>There are two ways to determine or be informed of the status of VoiceOver. The first way is to call the UIKit function UIAccessibilityIsVoiceOverRunning(). This returns a BOOL indicating if VoiceOver is active. The second way is to register for the UIAccessibilityVoiceOverStatusChanged notification. We will use both of these techniques to show a reset button in our detailed task view whenever VoiceOver is active:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-14-001.png" alt="" /></p>

<p>The first thing we will do is add the reset button to both the iPhone and iPad Nib files for the task view controller and connect its outlet and action. The reset button is just a UIButton with a custom image inserted into the task view as shown below:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-14-002.png" alt="" /></p>

<p>We can set the accessibility label for the button directly in Interface Builder:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-14-021.png" alt="" /></p>

<p>To ensure that the button is not normally visible we also set the hidden property in Interface Builder:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-14-003.png" alt="" /></p>

<p>Our view controller implements an IBOutlet property that is wired up to the button.</p>

<pre><code>@property (weak, nonatomic) IBOutlet UIButton *taskResetButton;
</code></pre>

<p>The button action is connected to the same taskResetAction we used previously to respond to the shaking motion event:</p>

<pre><code>- (IBAction)taskResetAction;
</code></pre>

<p>Now when our view first loads the viewDidLoad method in the view controller is used to configure the view. So we can use a call to UIAccessibilityIsVoiceOverRunning() to see if VoiceOver is already active and if so ensure our reset button is visible:</p>

<pre><code>self.taskResetButton.hidden = ! UIAccessibilityIsVoiceOverRunning();
</code></pre>

<p>That takes care of situations where VoiceOver is in use when our view loads but not if it is activated or disabled when our view is already onscreen. For that we need to register an observer for the notification in the viewDidLoad method:</p>

<pre><code>- (void)viewDidLoad
{
  ...
  ...

  [[NSNotificationCenter defaultCenter] addObserver:self 
                         selector:@selector(voiceOverStatusChanged)
                         name:UIAccessibilityVoiceOverStatusChanged
                         object:nil];
}
</code></pre>

<p>To be sure we clean up when our view controller goes away we should of course unregister the observer in viewDidUnload and dealloc. Since we are using ARC we have not so far implemented dealloc so we need to add it now just to remove the observer:</p>

<pre><code>- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}
</code></pre>

<p>The notification does not actually provide a parameter indicating the VoiceOver status but that is not an issue as we can simply call UIAccessibilityIsVoiceOverRunning again to get the current status. Depending on the status we can show or hide the reset button:</p>

<pre><code>- (void)voiceOverStatusChanged
{
  self.taskResetButton.hidden = ! UIAccessibilityIsVoiceOverRunning();
}
</code></pre>

<p>Now as we enable or disable VoiceOver with the task view visible the reset button is dynamically shown or hidden in response.</p>

<h3>Summary</h3>

<p>As I discussed at the start of this post if you find yourself needing to modify your app behaviour for VoiceOver it may actually be a warning of a more fundamental problem in your interface design. For those situations where you really do need to do something different I hope this post proves to be useful. You can find the modified Xcode project used in this post in my GitHub <a href="https://github.com/kharrison/CodeExamples/tree/master/TaskTimer">CodeExamples</a> repository.</p>
]]></description>
    </item>
    
    <item>
		  <title>Programming iOS 5 by Matt Neuburg</title>
		  <link>http://useyourloaf.com/blog/2012/05/10/programming-ios-5-by-matt-neuburg.html</link>
      <pubDate>Thu, 10 May 2012 22:14:00 +0100</pubDate>
		  <guid>http://useyourloaf.com/blog/2012/05/10/programming-ios-5-by-matt-neuburg.html</guid>
      
        <category>reviews</category>
      
      <description><![CDATA[<p><em><a href="http://shop.oreilly.com/product/0636920023562.do"><img src="http://akamaicovers.oreilly.com/images/0636920023562/cat.gif" align="right"></a>My list of book <a href="http://useyourloaf.com/links/">resources</a> has lacked a strong recommendation for iOS for some time. There are a lot of good introduction to iOS programming books available but I struggle to recommend just one as the definitive guide. <a href="http://shop.oreilly.com/product/0636920023562.do">Programming iOS 5</a>, 2nd Edition by Matt Neuburg (O&#8217; Reilly Media, March 2012) is a major update to the author&#8217;s earlier Programming iOS 4 book which may just fill the gap.</em></p>

<h3>First Impressions</h3>

<p>The first thing I have to say is that this is a massive book with the dead-tree version weighing in at 1016 pages. Luckily I read the ePub version using iBooks which I prefer for technical books. You are going to want to annotate, highlight and bookmark for future reference with this book. You can read it from cover-to-cover but it will also serve you well as a reference book when you need to review topics. Note though that if you are looking for a tutorial or cookbook style approach this is probably not the book for you. I guess Matt may have received some criticism for the iOS 4 version of the book as he makes the purpose of this edition very clear up front:</p>

<blockquote><p>The purpose of this book is to proceed by focusing on the underlying knowledge needed for an actual understanding of iOS programming. That is precisely the opposite of a cookbook. This book has no simple recipes ready for you to drop into your own code and come up with an app. I don&#8217;t give you some fish; I teach you what a fish is and what you need to know to obtain one.</p></blockquote>

<p>Even though it is not a cookbook all of the code examples are available on <a href="https://github.com/mattneub/Programming-iOS-Book-Examples">GitHub</a> which is an approach I wish all authors would adopt. It makes it so much easier to browse code and also ensures that any minor typos get fixed quickly. Emphasis is given to features new to iOS 5 such as ARC and storyboarding which helps if you are transitioning from iOS 4 but no prior iOS knowledge is assumed.</p>

<h3>In Depth</h3>

<p>The book is divided into seven major sections as follows:</p>

<ul>
<li>Section I. Language</li>
<li>Section II. IDE</li>
<li>Section III. Cocoa</li>
<li>Section IV. Views</li>
<li>Section V. Interface</li>
<li>Section VI. Some Frameworks</li>
<li>Section VII. Final Topics</li>
</ul>


<p>The first five sections represent maybe two thirds of the book and step by step provide a thorough coverage of the fundamentals of iOS 5 development. A lot of iOS programming books either assume prior knowledge of C or include a quick summary in an Appendix. This books kicks off with coverage of both the C and Objective-C languages and then introduces Xcode and Nibs.</p>

<p>With the basics out of the way Cocoa is introduced by way of the foundation framework, categories and protocols, notifications, the delegation pattern, actions and the responder chain. It is also at this point that the detailed discussion of memory management is introduced which is a mandatory and key topic for any Cocoa book. The book is written with the assumption that you will be using ARC but also stresses that you still need to understand the Cocoa memory management model behind ARC.</p>

<p>The Views section provides good explanations on the view hierarchy, frames and coordinate systems, drawing, layers, animation, handling touches and gestures. The Interface section completes the fundamentals with coverage of view controllers, table views, popovers and split views and an exhaustive look at the numerous other views and controls.</p>

<p>The last two sections of the book tie up some loose ends with coverage of additional frameworks and topics that don&#8217;t fit elsewhere. This includes coverage of many of the more common frameworks including audio, video, music library, photo library, address book, calendar, mail, maps and sensors (e.g. location and acceleration). The final section finishes up with some quick coverage of file management, networking and threads (including both NSOperation and Grand Central Dispatch). The use of iCloud is also covered briefly in the discussion on the UIDocument model.</p>

<h3>Likes and Dislikes</h3>

<p>What I like about this book are the numerous hints, tips and opinions from Matt as he covers each topic. I don&#8217;t want to see a reproduction of reference material that I can just as easily get from Apple. What I want is insight into what an experienced developer thinks about the topic at hand. For example, there is a very good explanation of storyboards but what I found interesting about that section was Matt&#8217;s strong opinion on storyboards and why you might not want to use them. The explanation on popovers gets a similar treatment and in both cases I have to agree with the conclusions that Matt reaches.</p>

<p>There were so many new features introduced with iOS 5 that I think even somebody with iOS 4 experience will find this book useful. Changes from iOS 4 are highlighted throughout the book which should help when making the transition.</p>

<p>Even though this is a huge book there are still some topics that are not covered. It is easy to forget how big the iOS SDK has become so I think it is fine to skip topics like Game Kit, iAD integration, Printing, In App Purchase and the long list of other iOS Frameworks and topics. If you have a good understanding of the basics you should have no problem figuring out the less common frameworks on your own.</p>

<p>Personally I would have liked to see Core Data and maybe also Accessibility covered. I consider Core Data to be a fundamental Cocoa technology and as I <a href="http://useyourloaf.com/blog/2012/04/23/voiceover-accessibility.html">posted recently</a> I would like to see Accessibility get some more attention in general from developers and book authors. Section VI of the book covers a number of interesting but not vital frameworks such as accessing the music and photo libraries, the address book and calendar which I would exchange for some coverage of Core Data. That is a very minor criticism though for what is otherwise a comprehensive coverage of the iOS universe.</p>

<h3>Final Comments</h3>

<p>There is a lot to recommend about this book and I don&#8217;t just mean because of the size. The primary purpose of the book is to provide you with a deep understanding of the language and iOS frameworks and I think it succeeds in that task. Of course that takes some effort on the part of the reader and I can imagine that this book will not suit everybody. Clearly if you are looking for quick high level survey of iOS 5 with some sample code to get you started this is not the book for you. On the other hand if you are prepared to invest the time I would be surprised if even experienced iOS developers can read this book without learning something.</p>
]]></description>
    </item>
    
    <item>
		  <title>Static Table Views with Storyboards</title>
		  <link>http://useyourloaf.com/blog/2012/05/07/static-table-views-with-storyboards.html</link>
      <pubDate>Mon, 07 May 2012 14:14:00 +0100</pubDate>
		  <guid>http://useyourloaf.com/blog/2012/05/07/static-table-views-with-storyboards.html</guid>
      
        <category>storyboard</category>
      
      <description><![CDATA[<p>When I first heard that iOS 5 had introduced the concept of a static table view that could be designed in Interface Builder I was disappointed to see that it was actually tied into storyboards. I have nothing against storyboards, they are an interesting innovation that can (potentially) save a lot of code. However if you are not yet ready to fully adopt storyboards for your user interface design you may be discouraged from exploring the new features they bring. What I want to examine in this post is how you can use a minimal implementation of storyboards to quickly create a static table view without having to completely rewrite an existing App.</p>

<h3>Designing A Settings Table</h3>

<p>Implementing a Settings table is an obvious use for static table views within an App. To illustrate how easy this is I am going to start from the Xcode template for a tabbed application. Note that I did not select the option to use storyboards so that the main interface is still created using the traditional Nib approach. (I am however using ARC so pay attention if you are cut and pasting code into an App not using ARC). The template gives us a tab bar controller containing two view controllers both loaded from individual Nib files. The second view controller is what we will replace with a storyboard to implement our application settings views.</p>

<p>To get started I am going to create a storyboard and layout a number of table views. To keep this post short I am going to limit this to an iPhone layout but the principle applies equally for an iPad or Universal App. To add a storyboard create a new file and select the storyboard from the User Interface templates, ensure the device family is set to iPhone and name the file <code>Settings</code>:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-03-001.png" alt="" /></p>

<p>The first table view controller that I am going to add to the storyboard is going to represent a top level settings menu allowing me to group simple and advanced settings which I will access on separate views. When I have finished the table view should look like this:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-03-002.png" alt="" /></p>

<p>By default when you drag a table view controller into a storyboard you get a dynamic table view. You can change this by selecting <code>Static Cells</code> in the Attributes Inspector:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-03-003.png" alt="" /></p>

<p>What we now have is a table view containing three empty cells that we can use to design our top level settings menu:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-03-004.png" alt="" /></p>

<p>To get to our desired layout the main steps are as follows:</p>

<ul>
<li>change the table view style from <code>Plain</code> to <code>Grouped</code> and delete two of the rows to leave a single row (you can change the number of rows using the Inspector but to delete a row it is quicker to just click on the rows in the table and hit the delete key)</li>
<li>drag a label object into the table view cell, adjust the formatting as you see fit and set the text label to <code>General</code></li>
<li>with the Table View Section selected in either the document navigator or in the jump bar use the Attributes Inspector to set the section header and footer (this is also where you would adjust the number of rows in the section):</li>
</ul>


<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-03-005.png" alt="" /></p>

<p>To add the second section ensure the Table View is selected in the document navigator and then change the number of sections in the Attributes Inspector. When the new section is added it is copied from the first section which is a nice time saver. To complete the layout we just need to modify the header, footer and label text.</p>

<p>Now we have our initial settings table view we can repeat the exercise to add our detailed settings tables but before we do that we need to embed our table view controller in a navigation controller to handle moving between the various tables. That is an easy step using the Embed In > Navigation Controller option from the Xcode Editor menu. Once the Navigation Controller has been added we can also set the title in the Navigation Bar for our Settings table view controller. At this point the Storyboard should look as follows:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-03-006.png" alt="" /></p>

<p>Now we can repeat the exercise for two additional table view controllers which will provide static table views for our simple and advanced settings. I will not go through this step by step but at the end of the process the Storyboard will look something like this:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-06-001.png" alt="" /></p>

<p>At this point we need to add the transitions from the Settings table view controller to each of the detailed settings view controllers. The Storyboard editor refers to each of the views as scenes and transitions between scenes as segues. We need two segues in this case, the first from the General table view cell to take us to the General Settings table view and the second from the Extra Settings table view cell to the Advanced Settings table view. To create the segues you need to control click on the source table view cell and then drag across to the destination table view. When you release the mouse button you are presented with a popover menu allowing you to select the Storyboard segue style. Since we are using a navigation controller we will use the push segue.</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-06-002.png" alt="" /></p>

<p>With our new view controllers now included in the navigation hierarchy we can set the title for each view by typing directly in the navigation bar of each view so that our Storyboard now looks as follows (Interface Builder will infer when it needs to add the navigation and tab bars to views):</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-06-003.png" alt="" /></p>

<h3>Loading the storyboard</h3>

<p>If we were using a storyboard for the main user interface we could specify the filename in the UIMainStoryboardFile key in the application Info.plist file and it would be loaded automatically. Since in this example we want to make a more limited use of storyboards we need to manually load and launch our storyboard file. We can do that by modifying our Application Delegate to use the storyboard when loading the view controller for the second tab bar item. The relevant code in the application:didFinishLaunchingWithOptions method is as follows:</p>

<pre><code>UYLFirstViewController *firstViewController = [[UYLFirstViewController alloc]
                        initWithNibName:@"UYLFirstViewController"
                        bundle:nil];
UIStoryboard *settingsStoryboard = [UIStoryboard 
                                    storyboardWithName:@"Settings"
                                    bundle:nil];
UIViewController *settingsViewConroller = [settingsStoryboard
                                        instantiateInitialViewController];

settingsViewConroller.title = NSLocalizedString(@"Settings", @"Settings");
settingsViewConroller.tabBarItem.image = [UIImage imageNamed:@"second"];

self.tabBarController = [[UITabBarControlleralloc] init];
self.tabBarController.viewControllers = [NSArray
                      arrayWithObjects:firstViewController,
                      settingsViewConroller, nil];
self.window.rootViewController = self.tabBarController;
</code></pre>

<p>Lines 2 and 3 are the important ones, the UIStoryboard class method storyBoardWithName:bundle: is used to load the Storyboard file. There is no need to specify the bundle when the storyboard is contained in the main application bundle. The instantiateInitialViewController method then allocates and initialises our root navigation view controller which we can then add to the tab bar view controller along with the first view controller which was created from its Nib file.</p>

<p>Now if we run the App in the Simulator a lot the Settings table view is already working including pushing and popping the detailed view controllers on and off the navigation controller stack. So far this looks like a real win for storyboards in that we have a lot of functionality designed in Interface Builder without having to write any boilerplate view controller code. Since our initial settings table view controller only acts as a top level menu it appears that we do not even need to implement a custom subclass for it (I say &#8220;appears&#8221; as we will see shortly that there is one issue we need to deal with that causes us to create a generic table view subclass).</p>

<h3>Implementing Row Selection</h3>

<p>To actually make our settings screens useful we need to implement the view controllers so that we can interact with the user interface and read and write the settings. The general settings screen (shown below) is the easiest so we will start by adding a subclass of UITableViewController named UYLGeneralSettingsTableViewController.</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-06-004.png" alt="" /></p>

<p>The public interface for this class is empty:</p>

<pre><code>@interface UYLGeneralSettingsTableViewController : UITableViewController
@end
</code></pre>

<p>We will add two properties to the private class extension to represent to two settings (speed and volume) that this view manipulates:</p>

<pre><code>@interface UYLGeneralSettingsTableViewController ()

@property (nonatomic) NSUInteger speed;
@property (nonatomic) NSUInteger volume;

@end
</code></pre>

<p>Now we need to implement just enough of a table view controller to allow us to setup the view state when it first loads and to allow us to change the selected row in each of the two sections. Before I show the code that I added it is important to note the code that I do NOT need to implement:</p>

<ul>
<li>the UITableViewDataSource protocol has two required methods and a number of optional methods that are now largely redundant. Of the two normally required methods I will in this case implement tableView:cellForRowAtIndexPath: (to set the checkmark of the selected row) but it may not always be required.</li>
<li>There is no need to implement the other required method tableView:numberOfRowsInSection: or numberOfSectionsInTableView: as the table dimensions of the static table were set in InterfaceBuilder.</li>
<li>We do not need to implement tableView:titleForHeaderInSection: or tableView:titleForFooterInSection: as we directly set the header and footer in the Storyboard.</li>
</ul>


<p>To initialise the view we will implement the viewDidLoad method to read our user defaults from file.</p>

<pre><code>- (void)viewDidLoad
{
    [superviewDidLoad];

    NSUserDefaults *defaults = [NSUserDefaultsstandardUserDefaults];
    self.speed = [defaults integerForKey:kUYLSettingsSpeedKey];
    self.volume = [defaults integerForKey:kUYLSettingsVolumeKey];
}
</code></pre>

<p>Now to actually set the checkmark on the currently selected row we will implement the UITableViewDataSource protocol method tableView:cellForRowAtIndexPath:</p>

<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [super tableView:tableView
                             cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;

    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];

    switch (section)
    {
        case SECTION_SPEED:
            if (row == self.speed)
            {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            }
            break;

        case SECTION_VOLUME:
            if (row == self.volume)
            {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            }
            break;
    }
    return cell;
}
</code></pre>

<p>Usually the first thing you do in tableView:cellForRowAtIndexPath is attempt to dequeue a cell for reuse of if not available allocate and initialise a new UITableViewCell. However that does not apply in this case as this is a static table view. All of the table view cells that we need were created in Interface Builder and are instantiated when the storyboard loads the view controller. By the way this is worth considering if you are attempting to use static table views to create a huge table view. Having to allocate all of the static table view cells when the view is first loaded may be both slow and cause you memory issues. If you find yourself creating a static table view with more than one or two screens of information you probably want to go back to using a dynamic table view.</p>

<p>Even though we do not need to allocate the table view cells for a static table view we can still get a reference to each cell to allow us to customise the cell. There are several ways to do this including declaring an outlet for each table view cell in Interface Builder which we will see in the advanced settings view controller. In this case though we simply need to set the cell accessory type so we can call tableView:cellForRowAtIndexPath on the super class to return us the current cell. Once we have the current cell we can set or clear the accessoryType based on the current value of the speed or volume properties.</p>

<p>We also need to implement the UITableViewDelegate method to handle row selection (see below). There is nothing remarkable about this method so I will not go into too much details. The method basically just updates the user defaults based on which row is selected and then requests the table view is reloaded to cause the checkmarks to be set.</p>

<pre><code>- (void)tableView:(UITableView *)tableView
        didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];

    switch (section)
    {
        case SECTION_SPEED:
            self.speed = row;
            [defaults setInteger:row forKey:kUYLSettingsSpeedKey];
            break;
        case SECTION_VOLUME:
            self.volume = row;
            [defaults setInteger:row forKey:kUYLSettingsVolumeKey];
            break;
    }
    [self.tableView reloadData];
}
</code></pre>

<p>Finally we need to go back to Interface Builder and with the Identity inspector change the class of the generic UITableViewController to our custom subclass UYLGeneralSettingsTableViewController:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-06-005.png" alt="" /></p>

<p>If you rerun the App in the Simulator the general settings screen should now be fully functional.</p>

<h3>Connecting to Static Table View Cells</h3>

<p>The advanced settings screen at first looks a little more complicated as we have a number of switches and stepper controls that we need to interact with. In fact whilst it takes a little bit of effort in Interface Builder wiring everything up it actually requires even less code. As before we will start by adding a subclass of UITableViewController to the project and name it UYLAdvancedSettingsViewController:</p>

<pre><code>@interface UYLAdvancedSettingsViewController : UITableViewController
@end
</code></pre>

<p>To be able to interact with the contents of the static table view cells we need to define some outlets to allow us to set the various elements and action methods for the switch and stepper controls. A good place to do that is in a private class extension of our custom subclass:</p>

<pre><code>@interface UYLAdvancedSettingsViewController ()

- (IBAction)switchToggled:(UISwitch *)sender;
- (IBAction)stepperChanged:(UIStepper *)sender;

@property (nonatomic, weak) IBOutlet UISwitch *warpSwitch;
@property (nonatomic, weak) IBOutlet UISwitch *shieldsSwitch;
@property (nonatomic, weak) IBOutlet UILabel *creditsLabel;
@property (nonatomic, weak) IBOutlet UILabel *retriesLabel;
@property (nonatomic, weak) IBOutlet UIStepper *creditsStepper;
@property (nonatomic, weak) IBOutlet UIStepper *retriesStepper;

@end
</code></pre>

<p>This project is compiled using ARC so we follow Apple recommendations and make all of our IBOutlet properties weak references. Now we use Interface Builder to connect the outlets to the corresponding label or control in the static table view. To do that we first need to use the Identity inspector to change the class of the view from the generic UITableViewController to our custom UYLAdvancedSettingsViewController. I will not walk you through wiring up every user interface element as it is standard Interface Builder stuff but just for reference the view hierarchy and connections are reproduced below:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-06-006.png" alt="" /></p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-06-007.png" alt="" /></p>

<p>In order to determine which switch or stepper is triggering the action each one is uniquely tagged within Interface builder.</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-06-008.png" alt="" /></p>

<p>Now we have our outlets wired up it is trivial in viewDidLoad to set the initial state of the switches, steppers and labels:</p>

<pre><code>- (void)viewDidLoad
{
  [superviewDidLoad];

  NSUserDefaults *defaults = [NSUserDefaultsstandardUserDefaults];

  self.warpSwitch.on = [defaults boolForKey:kUYLSettingsWarpDriveKey];
  self.shieldsSwitch.on = [defaults boolForKey:kUYLSettingsShieldsKey];

  self.creditsStepper.value = [defaults doubleForKey:kUYLSettingsCreditsKey];
  self.creditsLabel.text = [NSStringstringWithFormat:@"%1.0f",
                            self.creditsStepper.value];

  self.retriesStepper.value = [defaults doubleForKey:kUYLSettingsRetriesKey];
  self.retriesLabel.text = [NSStringstringWithFormat:@"%1.0f",
                            self.retriesStepper.value];
}
</code></pre>

<p>Note that we do not need to implement tableView:cellForRowAtIndexPath: to get a cell reference as we have direct access to each cell via the outlets. In fact we do not need to implement any UITableViewDataSource or UITableViewDelegate method. The two action methods to handle the switch and stepper actions are fairly similar so I will just show the method for the switch here:</p>

<pre><code>- (IBAction)switchToggled:(UISwitch *)sender
{
    NSUserDefaults *defaults = [NSUserDefaultsstandardUserDefaults];

    switch (sender.tag)
    {
        case TAG_WARPSWITCH:
            [defaults setBool:sender.on forKey:kUYLSettingsWarpDriveKey];
            break;

        case TAG_SHIELDSSWITCH:
            [defaults setBool:sender.on forKey:kUYLSettingsShieldsKey];
            break;
    }
}
</code></pre>

<h3>Handling Orientation Changes</h3>

<p>There is one small issue I need to take care of before finishing. As currently implemented there is a problem with the way that we respond to device rotation. In fact if you build and run the App you will see that it does not respond to device orientation changes. The general rule for a tab bar controller is that all of the view controllers in each tab need to allow rotation or nothing rotates. I have not shown it but each of the view controllers we have implemented, including the view controller used for the first tab bar item, implements shouldAutorotateToInterfaceOrientation: to return YES for all orientations:</p>

<pre><code>- (BOOL)shouldAutorotateToInterfaceOrientation:
        (UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}
</code></pre>

<p>Unfortunately there is one view controller, the top level settings table view controller which messes things up for us. Since we did not need to interact with the table we never actually implemented our own custom subclass for this table view controller. That means we cannot override the orientation method so we get the default behaviour:</p>

<blockquote><p>By default, this method returns YES for the UIInterfaceOrientationPortrait orientation only. If your view controller supports additional orientations, override this method and return YES for all orientations it supports.</p></blockquote>

<p>To resolve this issue I have added a new UITableViewController subclass named UYLRotatingTableViewController that does nothing else but implement the shouldAutorotateToInterfaceOrientation method. Using the Identity inspector to change the class of the settings table view controller to this new subclass fixes the problem. The final storyboard is as follows:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-05-07-001.png" alt="" /></p>

<h3>Wrapping Up</h3>

<p>One of the criticisms I have heard about storyboards is that unless your App is very simple they do not save you very much code. This is because you still need to handle the flow of data between view controllers. Typically this involves implementing prepareForSeque:Sender: to pass data into a new view controller and implementing a delegate protocol to pass data back to a parent or presenting view controller.</p>

<p>In this example we are making a very limited use of storyboards and there is no real data flow between the different static table view controllers. This means there is no need to implement prepareForSegue:sender: or to create view controller delegates so there is a considerable reduction in the amount of code required. You can make your own mind up on the value of storyboards and when they might be appropriate. Personally I like the ability to add them selectively to an App for specific parts of the interface and static table views are definitely one area where I will use them.</p>

<p>As always you can download the example Xcode project that accompanies this post <a href="http://useyourloaf.com/assets/code/StaticTable.zip">here</a> or in my Github <a href="https://github.com/kharrison/CodeExamples/tree/master/StaticTable">CodeExamples</a> repository.</p>
]]></description>
    </item>
    
    <item>
		  <title>Xcode Balancing Brackets For Method Calls</title>
		  <link>http://useyourloaf.com/blog/2012/04/27/xcode-balancing-brackets-for-method-calls.html</link>
      <pubDate>Fri, 27 Apr 2012 20:18:00 +0100</pubDate>
		  <guid>http://useyourloaf.com/blog/2012/04/27/xcode-balancing-brackets-for-method-calls.html</guid>
      
        <category>Xcode</category>
      
      <description><![CDATA[<p><em>This may well be my favourite and perhaps also the simplest Xcode completion trick I have come across. I may be the last person to discover it but just in case there is somebody else who is yet to find it&#8230;</em></p>

<p>I always find it a pain to think about how many opening brackets (&#8220;[&#8220;) I need when starting to write Objective-C statements where you have several nested method calls. This means I often get to the end of the statement and find I have an extra opening bracket somewhere. Luckily Xcode will allow you to forget about the opening brackets and just type the closing brackets. The corresponding opening bracket is inserted for you by Xcode automatically. So for example assume I start typing the following sequence:</p>

<pre><code>NSNumber *number10 = NSNumber alloc
</code></pre>

<p>At this point (with the cursor at the end of the line) typing a single closing bracket &#8220;]&#8221; causes Xcode to insert the corresponding opening bracket so you end up with this:</p>

<pre><code>NSNumber *number10 = [NSNumber alloc]
</code></pre>

<p>If I then continue to type the rest of the statement I can repeat the same trick at this point:</p>

<pre><code>NSNumber *number10 = [NSNumber alloc] initWithInteger:10 
</code></pre>

<p>Typing the final closing &#8220;]&#8221; again causes Xcode to insert the corresponding initial &#8220;[&#8221; to give us the following:</p>

<pre><code>NSNumber *number10 = [[NSNumber alloc] initWithInteger:10]
</code></pre>

<p>Adding the final semicolon completes the statement:</p>

<pre><code>NSNumber *number10 = [[NSNumber alloc] initWithInteger:10];
</code></pre>

<p>If for some strange reason you do not like this code completion you can disable it in Xcode preferences (look under Code completion in the Text Editing preferences pane).</p>
]]></description>
    </item>
    
    <item>
		  <title>VoiceOver Accessibility</title>
		  <link>http://useyourloaf.com/blog/2012/04/23/voiceover-accessibility.html</link>
      <pubDate>Mon, 23 Apr 2012 19:47:00 +0100</pubDate>
		  <guid>http://useyourloaf.com/blog/2012/04/23/voiceover-accessibility.html</guid>
      
        <category>accessibility</category>
      
      <description><![CDATA[<p>Apple has made it really easy to add VoiceOver support to iOS Apps. In many cases setting the accessibility label for each interface element in Interface Builder gets 90% of the job done. What I want to cover in this post is the remaining 10% that will ensure an App interacts well with VoiceOver. If you have never considered making your App accessible you should read this great post by Matt Gemmell on <a href="http://mattgemmell.com/2010/12/19/accessibility-for-iphone-and-ipad-apps/">Accessibility for iPhone and iPad apps</a>.</p>

<h3>What is VoiceOver?</h3>

<p>VoiceOver is a technology built into all iOS (and Mac) devices that provides audible aids to the user when navigating and interacting with an App. The UIAccessibility API was introduced with version 3.0 of the SDK to allow the app to provide additional information to VoiceOver. This includes such things as setting the label and optionally a hint that is read by VoiceOver when an element in the user interface is selected. In addition you set accessibility traits for each UI element indicating for example that it acts like a button or whether or not it has been selected.</p>

<p>The easiest way to understand VoiceOver is to try it on some existing apps and get a feel for how it works. Before diving into an example app I will quickly review how to access VoiceOver and some other tools that you will want to use when testing your App.</p>

<h3>Toggling VoiceOver Support on a Device</h3>

<p>You can turn VoiceOver support on for a device from the Settings application (Settings > General > Accessibility > VoiceOver). However for testing purposes I find it more convenient to be able to quickly switch VoiceOver on and off from within the App. To do that I set the Triple-click Home button option to Toggle VoiceOver (from the Settings > General > Accessibility screen):</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-03-27-voiceover.png" alt="" /></p>

<p>With this option enabled you can easily turn VoiceOver on and off at any point by triple-clicking the Home button on the device. This makes it easy to examine specific situations in your App with and without VoiceOver activated. It can also be an education to enable VoiceOver on other Apps to see how well or badly other developers are handling accessibility.</p>

<h3>Accessibility Inspector in the iOS Simulator.</h3>

<p>The iOS Simulator does not directly support VoiceOver so you will always need to test on a device to see how well your App performs. However the iOS Simulator does have an extremely useful tool for debugging UIAccessibility issues. It is called the Accessibility Inspector and it can be activated on the Simulator from Settings > General > Accessibility. Once enabled you should see the inspector window displayed:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-03-27-inspector.png" alt="" /></p>

<p>The Accessibility Inspector does not speak to you but it does provide you with information about the currently selected accessible element. The Inspector can be temporarily disabled/enabled by clicking the close control in the upper left corner of the Inspector. This can be useful when you need to navigate around the app as you can selectively enable the inspector to examine each element in your user interface.</p>

<h3>TaskTimer - An Example in Adding Accessibility</h3>

<p>The rest of this post is going to be a case study in adding VoiceOver support to an example App called TaskTimer. The app is based on the Xcode Master Detail template and is a variation on a task list manager - the variation being that you can time how long a particular task takes. This is a universal app so both iPhone and iPad User Interfaces are supported. The master view is a UITableView containing the list of tasks as shown in the iPhone screenshot below:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-04-07-001.png" alt="" /></p>

<p>The task list follows the usual conventions of a table view in that new tasks can be inserted using the &#8220;+&#8221; button in the navigation bar and deleted via the &#8220;Edit&#8221; button. The actual task data is stored in a core data model. A completed task is shown by the green tick and the actual duration (mm:ss) is shown under the task name in the table cell view. The App is somewhat limited in that it only handles task durations up to 59 minutes 59 seconds long but it is good enough for the purposes of this post. Selecting a row in the table shows the detail view for the selected task which allows the task name to be edited. In addition a custom view allows the task timer to be stopped and started via two buttons with the current task duration displayed in a central text label:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-04-07-002.png" alt="" /></p>

<p>As I mentioned this is a Universal app so just for completeness the iPad user interface is shown below in portrait orientation:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-04-07-003.png" alt="" /></p>

<h3>UITableView Accessibility</h3>

<p>If we use the Accessibility Inspector in the iOS Simulator we can see how well this App performs before we make any modifications. If we first take a look at the Task List table view we can find some UI elements that work fine and others that definitely need some work. The standard Navigation bar elements such as the Edit button, the title and the Add button all work fine without any effort on our part:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-04-09-001.png" alt="" /></p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-04-09-002.png" alt="" /></p>

<p>Note how the accessibility traits indicate that the first UI element is a button where as the second element is static text. Correctly setting the accessibility traits of an element is key to ensuring that VoiceOver interacts correctly with the App. Standard iOS UIKit elements such as the Navigation Bar are generally already properly configured. Simple UI elements can also be configured in Interface Builder when creating the interface.</p>

<p>Things are not so good if we look at one of the rows in the table for a completed task:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-04-09-003.png" alt="" /></p>

<p>By default the table view cell has combined the main text label and the detailed text label for the accessibility label. The two fields are separated by a comma which means VoiceOver will pause briefly when reading the label. This is fine but VoiceOver does not understand that 00:10 actually means 0 minutes, 10 seconds - it simply reads &#8220;zero - ten&#8221; which is not very informative. Note also that there is no mention of the status of the task. In this case the green tick indicates that the task has been completed but the VoiceOver interface is unable to present that piece of information to the user.</p>

<p>So to improve the accessibility of this view we should in the first instance address the following issues:</p>

<ul>
<li>Ensure that when VoiceOver reads the task details it correctly interprets the duration making it clear that it is a time.</li>
<li>We should also ensure that the task completion status is indicated for each row in the list</li>
</ul>


<p>One thing we could also do is add a hint to the table view cell indicating that selecting a row will take the user to the detail task view. In this case I consider that unnecessary as I think it is OK to assume that users understand the basic iOS user interface idioms.</p>

<p>To customise the response from VoiceOver for a UITableView cell we simply need to set the accessibilityLabel property when we configure the cell in the table view controller. In the situation where the task is not yet completed and so does not have a final duration we will stick with the default provided by the cell text label which is the name of the task (task.note). However when the task is complete (task.complete) we want to both indicate the completion status and read the duration in a human friendly way. The following code added to the configureCell:atIndexPath method in UYLTaskListViewController should do the job:</p>

<pre><code>cell.accessibilityLabel = task.note;

if ([task.complete boolValue])
{
  NSUInteger minutes = [task.duration integerValue] / 60;
  NSUInteger seconds = [task.duration integerValue] % 60;

  cell.detailTextLabel.text = [NSString stringWithFormat:@"%02u:%02u",
                               minutes, seconds];
  cell.imageView.image = [UIImage imageNamed:@"checked.png"];

  NSString *durationText = [NSString stringWithFormat:@"%@ %@",
                            task.note,
                            NSLocalizedString(@"completed in", nil)];
  durationText = [durationText stringByAppendingString:
                               [task.duration stringValueAsTime]];
  cell.accessibilityLabel = durationText;
}
</code></pre>

<p>To generate the text to represent the duration I have created a category (UYLTimeFormatter) on the NSNumber class to add the method stringValueAsTime since we will need it more than once. An example of the output using the Accessibility Inspector is shown below:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-04-11-001-1.png" alt="" /></p>

<h3>Custom View Accessibility</h3>

<p>So far adding VoiceOver support has been very easy since it has just involved setting the accessibilityLabel for certain key UI elements. However for the detailed task view things get slightly more complicated. A custom class UYLCounterView is used to implement the numeric counter and the two buttons used to start and stop the counter. By default the buttons will use either the title if set or the name of the UIImage file to provide an accessibility label.  In this case I am using images named start.png and stop.png which provides a reasonable default but note that these labels are of course not localised.</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-04-18-001.png" alt="" /></p>

<p>A more serious problem though is that the value of the counter is not accessible at all. The problem is that the text is drawn in the view using a drawAtPoint method so there is no way to directly set an accessibilityLabel or other accessibility properties for the counter. The solution is to implement the <strong>UIAccessibilityContainer Protocol</strong> for the custom view. This allows us to define arbitrary rectangles in the view that represent the elements we want to make accessible. In this case the view contains three elements, the start button, the stop button and the counter that we want to make accessible.</p>

<p>The UIAccessibilityContainer protocol is an informal protocol so we do not need to declare anything in our UYLCounterView class indicating that we are adopting it. What we will need though is a mutable array to hold our accessible elements. The following property is added to the UYLCounterView interface definition:</p>

<pre><code>@property (nonatomic, strong) NSMutableArray *accessibleElements;
</code></pre>

<p>We need to create and configure a UIAccessibilityElement object for each of the three elements in our custom view and store them in this array. To avoid unnecessary effort when VoiceOver is not active we will lazily create them in the getter method in the UYLCounterView implementation. The first thing we do therefore in the getter is to check if we have already created the array and if not we allocate it:</p>

<pre><code>- (NSArray *)accessibleElements
{
  if (_accessibleElements != nil)
  {
      return_accessibleElements;
  }

  _accessibleElements = [[NSMutableArray alloc] init];
</code></pre>

<p>Now we need to create a UIAccessibilityElement and correctly set the accessibility properties for each view element. We need to add the elements to the accessibleElements array in the order they are presented to the user from top-left to bottom-right. So the first element we will create is for the start button:</p>

<pre><code>  UIAccessibilityElement *startElement = [[UIAccessibilityElement alloc]
                          initWithAccessibilityContainer:self];
  startElement.accessibilityFrame = [self convertRect:self.startButton.frame
                                     toView:nil];
  startElement.accessibilityLabel = NSLocalizedString(@"Start", nil);
  startElement.accessibilityTraits = UIAccessibilityTraitButton;
  if (self.startButton.enabled == NO)
    startElement.accessibilityTraits |= UIAccessibilityTraitNotEnabled;

  [_accessibleElements addObject:startElement];
</code></pre>

<p>Some notes about each of the above lines of code</p>

<ul>
<li><p>A UIAccessibilityElement is created using the initWithAccessibilityContainer instance method. This method takes a single parameter which is the containing view. In this case the UYLCounterView is the containing view so we can simply use self.</p></li>
<li><p>The accessibilityFrame property is where we specify the area of the view that we want to use for this accessibility element. For the start button this is just the frame of the UIButton but note that <strong>the accessibility frame must be specified in screen coordinates</strong>. This is an important point to understand, if you use the view coordinate system you will get unexpected results especially when the view rotates (more on handling view rotation later). The easiest way to convert the button frame to the screen coordinates is to use the UIView instance method convertRect:toView: specifying nil as the target view, this will give us a frame in the screen coordinate system.</p></li>
<li><p>Once we have an accessibility element allocated we can set the accessibilityLabel as with standard UIKit controls. We can, if required, also set an accessibilityHint but in this case we will just set the label to &#8220;Start&#8221;.</p></li>
<li><p>The accessibilityTraits property is this case indicates that this element behaves as a button</p></li>
<li><p>We need to provide VoiceOver with a indication when the button is enabled/disabled. Usually a UIButton will take care of this for us but since we are creating our own accessibility element to represent the button we need to add the UIAccessibilityTraitNotEnabled trait when the button is not enabled.</p></li>
<li><p>Finally we add the element to our array of accessibileElements.</p></li>
</ul>


<p>The next element represents the text drawn in the centre of the view for the timer counter. Calculating the frame for the text is complicated by the need to convert between the view and screen coordinate systems. The code to create the accessibilityElement for the counter is as follows:</p>

<pre><code>CGRect frame = [self convertRect:self.accessibilityFramefromView:nil];

UIAccessibilityElement *counterElement = [[UIAccessibilityElement alloc]
                        initWithAccessibilityContainer:self];
CGRect textFrame = CGRectInset(frame, UYLCOUNTERVIEW_MARGIN + 
                                      self.startButton.bounds.size.width +
                                      UYLCOUNTERVIEW_MARGIN,
                                      UYLCOUNTERVIEW_MARGIN);
counterElement.accessibilityFrame = [self convertRect:textFrame toView:nil];
counterElement.accessibilityLabel = NSLocalizedString(@"Duration", nil);
counterElement.accessibilityValue = [[NSNumber
                                      numberWithInteger:self.secondsCounter]
                                      stringValueAsTime];
counterElement.accessibilityTraits = UIAccessibilityTraitUpdatesFrequently;

[_accessibleElements addObject:counterElement];
</code></pre>

<p>Note that in this case we start by converting the accessibilityFrame of the view to our local view coordinate system from the screen coordinate system. We can then calculate the frame for the text using an inset for the margin and size of the buttons. Finally before setting the accessibilityFrame for the element we need to convert back again to screen coordinates.</p>

<p>As well as setting the accessibilityLabel for this element we also set an accessibilityValue string to represent the current value of the counter. We will see how this gets updated later but note that for elements that can have a value which changes (such as volume control) it is better to use the accessibilityLabel to describe the function of the control and accessibilityValue to represent the current value. In this case the label is set to &#8220;Duration&#8221; and the value will the actual value of the counter (for example &#8220;2 minutes 10 seconds&#8221;).</p>

<p>Since the value of the counter can update frequently (in this case once a second) we set the UIAccessibilityTraitUpdatesFrequently trait. We will discuss the impact of this attribute and some other options once we have seen the rest of the setup code.</p>

<p>Finally we add the element for the stop button and return the completed array. Since the stop button code is very similar to the code for the start button I will include the code without further comment:</p>

<pre><code>  UIAccessibilityElement *stopElement = [[UIAccessibilityElement alloc]
                                  initWithAccessibilityContainer:self];
  stopElement.accessibilityFrame = [self convertRect:self.stopButton.frame
                                    toView:nil];
  stopElement.accessibilityLabel = NSLocalizedString(@"Stop", nil);
  stopElement.accessibilityTraits = UIAccessibilityTraitButton;
  if (self.stopButton.enabled == NO)
     stopElement.accessibilityTraits |= UIAccessibilityTraitNotEnabled;

  [_accessibleElements addObject:stopElement];

  return_accessibleElements;
}
</code></pre>

<p>With the accessibileElements defined we need to implement three very simple access methods required by the UIAccessibilityContainer protocol. These methods provide an interface to our accessibileElements array:</p>

<pre><code>- (NSInteger)accessibilityElementCount
{
  return [[self accessibleElements] count];
}

- (id)accessibilityElementAtIndex:(NSInteger)index
{
    return [[self accessibleElements] objectAtIndex:index];
}

- (NSInteger)indexOfAccessibilityElement:(id)element
{
    return [[self accessibleElements] indexOfObject:element];
}
</code></pre>

<p>To ensure the UIAccessibilityContainer protocol and our newly defined accessibileElements take effect we need to ensure that the UYLCounterView does not itself respond to accessibility requests. To do that we need to implement the isAccessibilityElement for the custom view and ensure it returns NO:</p>

<pre><code>- (BOOL)isAccessibilityElement
{
  return NO;
}
</code></pre>

<p>We still have a few refinements to make but we already have enough of an implementation to make our custom view accessible. The Accessibility Inspector now gives us a result when we select the counter text as follows:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-04-22-001.png" alt="" /></p>

<h3>Updating the Counter Value</h3>

<p>When we created the UIAccessibilityElement for the counter text we set the accessibilityValue property to the current value of the counter. Since the counter is updated every second when the counter is running we need to ensure that we also update the accessibilityValue. We can easily do that in the setter for the secondsCounter value maintained by the UYLCounterView:</p>

<pre><code>- (void)setSecondsCounter:(NSUInteger)secondsCounter
{
  if (secondsCounter &gt; UYLCOUNTERVIEW_LIMIT)
  {
      secondsCounter = UYLCOUNTERVIEW_LIMIT;
  }

  _secondsCounter = secondsCounter;

  if (_accessibleElements)
  {
      UIAccessibilityElement *counterElement = [self.accessibleElements
        objectAtIndex:UYLCOUNTERVIEW_ELEMENTINDEX_COUNTERTEXT];
      counterElement.accessibilityValue = [[NSNumber
                                          numberWithInteger:secondsCounter]
                                          stringValueAsTime];
  }

  [self setNeedsDisplay];
}
</code></pre>

<p>Note that that accessibleElements array should only be allocated via the getter method we saw previously when VoiceOver is active. We therefore use the ivar to check if it has been allocated before attempting to access it. After retrieving the UIAccessibilityElement for the counter we then set the accessibilityValue using our NSNumber stringValueAsTime category method.</p>

<h3>Setting UIButton Traits</h3>

<p>The next refinement we need to make is to update the accessibility traits for the two UIButton controls. When the start button is used it disables itself and enables the stop button. We can update the accessibilityTraits of the corresponding UIAccessibilityElement in the method that is triggered by the UIButton action to indicate to VoiceOver which buttons are enabled:</p>

<pre><code>- (void)startAction:(UIButton *)sender
{
  ...
  ...

  if (_accessibleElements)
  {
      UIAccessibilityElement *startElement = [self.accessibleElements
                  objectAtIndex:UYLCOUNTERVIEW_ELEMENTINDEX_STARTBUTTON];
      startElement.accessibilityTraits = UIAccessibilityTraitButton |
                                         UIAccessibilityTraitNotEnabled;

      UIAccessibilityElement *stopElement = [self.accessibleElements
                    objectAtIndex:UYLCOUNTERVIEW_ELEMENTINDEX_STOPBUTTON];
      stopElement.accessibilityTraits = UIAccessibilityTraitButton;        
  }
  ...
  ...
}
</code></pre>

<p>Likewise when the stop button is used it disables itself so we also need to set the accessibility trait to indicate the new button state:</p>

<pre><code>- (void)stopAction:(UIButton *)sender
{
  ...

  if (_accessibleElements)
  {
      UIAccessibilityElement *stopElement = [self.accessibleElements
                   objectAtIndex:UYLCOUNTERVIEW_ELEMENTINDEX_STOPBUTTON];
      stopElement.accessibilityTraits = UIAccessibilityTraitButton |
                                        UIAccessibilityTraitNotEnabled;
  }
  ...
}
</code></pre>

<h3>Handling View Rotation</h3>

<p>I am not sure why but most accessibility example Apps do not support device orientation changes. I can only suspect that this is due to the extra complexity involved in dealing with the conversion between screen and view coordinate systems. The implementation of the accessibileElements getter in our UYLCounterView takes this conversion into account when calculating the accessibilityFrame for each element. This ensures that the frame is set correctly based on the device orientation at the time the getter is invoked. There is however a problem if the orientation changes once we have calculated the frame. Since we never recalculate these frames they will no longer be correct if the orientation changes. To illustrate the problem this is how the accessibilityFrame for the counter text appears if we rotate from portrait to landscape:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-04-22-002.png" alt="" /></p>

<p>To fix this problem we need to force the accessibility frames to be recalculated when the device orientation changes. The easiest way I have found to do that is to detect the orientation change in the view controller and force the accessibleElements array to be recreated. To detect the orientation change in the UYLTaskViewController we can implement the didRotateFromInterfaceOrientation method:</p>

<pre><code>- (void)didRotateFromInterfaceOrientation:
        (UIInterfaceOrientation)fromInterfaceOrientation
{
  self.taskCounterView.accessibleElements = nil;
}
</code></pre>

<p>Now the next time that the accessibleElements array is accessed it will be created from scratch and the frames that are created will be based on the new orientation. We can check that with the inspector with the simulator in landscape:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-04-22-003.png" alt="" /></p>

<h3>Notifications</h3>

<p>When I covered the creation of the UIAccessibilityElement for the text counter I mentioned that we were using the UIAccessibilityTraitUpdatesFrequently trait but I did not fully describe the effect that this achieves. To fully understand how VoiceOver works in this case you will need to build the example App and install it on a physical device. With the text element selected VoiceOver announces the changing timer value every few seconds. In this case that turns out to be a good choice as the value is changing too quickly for VoiceOver to keep up. In my testing I found that VoiceOver would announce a new value every 4-5 seconds. Note that a new announcement is only made when the value is actually changing so if the time is stopped the announcements also stop. If you take a look at how the StopWatch function within the Apple Clock App works you will find that it also uses a similar technique.</p>

<p>However if we wanted to force VoiceOver to announce every change to the counter view we can tell it that something has changed by posting a notification. The notifications used by VoiceOver are a little different from the usual iOS notifications. To create a notification you need to use a UIKit function named <strong>UIAccessibilityPostNotification</strong>. This function takes two parameters, the first to specify the notification type and the second an optional notification specific parameter which is usually nil.</p>

<p>To indicate that something on the screen has changed we have two choices for the notification type. The first possibility is to send a <strong>UIAccessibilityLayoutChangedNotification</strong> to indicate that one or more, but not all, elements on the screen have changed. The other possibility is to send a <strong>UIAccessibilityScreenChangedNotification</strong> to indicate that the whole screen has changed and VoiceOver should reset. In this case we are only changing the duration text so we could send the layout changed notification by inserting the following function call into the setter method setSecondsCounter:</p>

<pre><code>UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification,
                                nil);
</code></pre>

<p>To test this change I also removed the UIAccessibilityTraitUpdatesFrequently trait from the text element. When run on the device VoiceOver does indeed attempt to announce the value of the duration every time it changes. Of course since it takes longer than a second to announce the duration it quickly falls behind which is not very useful. So in this situation where the value of an element is changing faster than VoiceOver can announce the changes it is better to use the UIAccessibilityTraitUpdatesFrequently trait.</p>

<p>Whilst on the subject of notifications there is another option which can be useful when you need to make an announcement for an event that does not update the user interface. You can post a UIAccessibilityAnnouncementNotification which causes VoiceOver to announce the NSString that is passed as the second parameter:</p>

<pre><code>UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification,
                                @"Hello World");
</code></pre>

<h3>Wrapping Up</h3>

<p>This has been a long post but I hope that if you have made it this far I have convinced you that adding accessibility support to your App is not difficult. If you do not have custom views it is often trivial and requires minimal coding. Even if you do have custom views creating the necessary accessibility container elements is not much more effort. The key point to remember is that the accessibility frames need to be specified in screen coordinates.</p>

<p>The example App that I used for this post can be found <a href="http://useyourloaf.com/assets/code/TaskTimer.zip">here</a> or in my Github <a href="https://github.com/kharrison/CodeExamples/tree/master/TaskTimer">CodeExamples repository</a>. I hope you found this post useful and that it will encourage you to ensure your Apps play nice with VoiceOver.</p>
]]></description>
    </item>
    
    <item>
		  <title>Splitview controller is expected to have a master view controller</title>
		  <link>http://useyourloaf.com/blog/2012/04/06/splitview-controller-is-expected-to-have-a-master-view-contr.html</link>
      <pubDate>Fri, 06 Apr 2012 14:58:00 +0100</pubDate>
		  <guid>http://useyourloaf.com/blog/2012/04/06/splitview-controller-is-expected-to-have-a-master-view-contr.html</guid>
      
        <category>splitviewcontroller</category>
      
      <description><![CDATA[<p>Whilst playing with the Master Detail Application template provided with Xcode 4.3.2 I came across an odd error message for the split view controller class. The problem happens when you implement the UISplitViewControllerDelegate method that specifies whether the master view controller should be hidden in a given orientation. The <em>splitViewController:shouldHideViewController:inOrientation</em> method was introduced in iOS 5.0 and is useful when you want to change the default behaviour which hides the master view in portrait mode. See this earlier post on <a href="http://useyourloaf.com/blog/2011/10/19/ios-5-split-view-controller-changes.html">iOS 5 split view controller changes</a> for the full details.</p>

<p>To reproduce the problem create a new project using the Master Detail Application template and implement the following method in the DetailViewController:</p>

<pre><code>- (BOOL)splitViewController:(UISplitViewController *)svc
   shouldHideViewController:(UIViewController *)vc
              inOrientation:(UIInterfaceOrientation)orientation {
  return YES;
}
</code></pre>

<p>Now when you run the project in the iPad Simulator you get the following error message logged to the console:</p>

<pre><code>Splitview controller &lt;UISplitViewController: 0xbec57e0&gt; is expected to have
a master view controller before its used!
</code></pre>

<p>Clearly an attempt to use a split view controller without giving it the two view controllers that it expects would be a serious error and probably deserves an immediate abort. However in this case we are using unmodified template code from Apple which does configure the split view controller with both a master and detail controller. The App also appears to run fine so the warning message does at first seem puzzling.</p>

<p>I noticed a while back that Apple changed the style of many of the example iOS projects to construct the initial root view controller interface in code rather than load it via a NIB file. The Master Detail application template also follows that trend. The following code snippet is from the point in the application delegate where the UISplitViewController is allocated and configured with its delegate and the two view controllers for the master and detail views:</p>

<pre><code>- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  ...
  ...
  self.splitViewController = [[UISplitViewController alloc] init];
  self.splitViewController.delegate = detailViewController;
  self.splitViewController.viewControllers = [NSArray
                           arrayWithObjects:masterNavigationController,
                           detailNavigationController, nil];
  ...
  ...
}
</code></pre>

<p>This looks fine but notice that the split view controller delegate is set before the viewControllers. This seems to be the source of the problem and if you reverse the two lines as shown below the warning message disappears:</p>

<pre><code>  self.splitViewController = [[UISplitViewController alloc] init];
  self.splitViewController.viewControllers = [NSArray
                           arrayWithObjects:masterNavigationController,
                           detailNavigationController, nil];
  self.splitViewController.delegate = detailViewController;
</code></pre>

<p>So it seems that the UISplitViewController performs some work in the setter for the delegate property and that this relies on the viewControllers already being set. I cannot find anything in the documentation that mentions this and it appears that whoever wrote the Xcode template was also unaware of this requirement.</p>

<p>In this case it does not seem to be a serious issue and the fix is trivial but if you come across this error message you may want to check if you have your viewControllers configured before you set the split view controller delegate. In the meantime I am thinking this is worth a bug report to Apple to see if they can provide some clarification in the UISplitViewController class documentation.</p>
]]></description>
    </item>
    
    <item>
		  <title>Updating for iPad retina display</title>
		  <link>http://useyourloaf.com/blog/2012/03/16/updating-for-ipad-retina-display.html</link>
      <pubDate>Fri, 16 Mar 2012 22:15:00 +0000</pubDate>
		  <guid>http://useyourloaf.com/blog/2012/03/16/updating-for-ipad-retina-display.html</guid>
      
        <category>iPad</category>
      
      <description><![CDATA[<p>Well today was the day that people started to get their hands on the third generation iPad with a double resolution retina display. Below are my notes on the minimal updates that you should consider making to best support all of those extra pixels.</p>

<h3>Custom Application Images</h3>

<p>Apple takes care of the UIKit images for standard iOS controls but if you have any custom images specific to the iPad you will as with the iPhone 4 need to supply @2x versions. I know many developers were sensibly preparing for this ahead of time by updating their iOS 5.0 built apps with double resolution images in the hope that they would just work on the new iPad. However there is one important caveat that can nicely summarised by this <a href="https://twitter.com/#!/Jury/status/180367953001324547">tweet</a> from Michael Jurewitz (@Jury):</p>

<pre><code>PSA - If you want your retina graphics to show up on the new iPad, you NEED
to build with Xcode 4.3.1 and __link against the 5.1 SDK__
</code></pre>

<h3>Application Icons</h3>

<p>The next most obvious update you need to do is provide a double resolution version of the main App icon. Apps that still only have a single resolution icon will stick out like a sore thumb on a retina display iPad.</p>

<p>There seems to be an a never-ending and growing list of dimensions that you need to supply for the application icon and the iPad retina display adds to that list. You should consult the <a href="https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/App-RelatedResources/App-RelatedResources.html#//apple_ref/doc/uid/TP40007072-CH6-SW1">iOS App Programming Guide</a> and <a href="https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/IconsImages/IconsImages.html#//apple_ref/doc/uid/TP40006556-CH14-SW1">iOS Human Interface Guidelines</a> for the comprehensive list but as a minimum you should at least include a new App icon and search results icon for the iPad retina display as follows:</p>

<h3>iPad App icon (144x144 pixels)</h3>

<p>The standard resolution main App icon for the iPad is 72x72 pixels. The retina display requires a @2x variant that is therefore 144x144 pixels.</p>

<h3>iPad Search results icon (100x100 pixels)</h3>

<p>The search results icon is used on the search results page and at standard resolutions is 50x50 pixels on the iPad. The @2x variant for the retina display version of the iPad is therefore 100x100 pixels.</p>

<h3>Filenames and Info.plist</h3>

<p>Depending on the level of backward compatibility that you need to maintain you may need to use specific naming conventions or add the new icon files to the application Info.plist file.</p>

<p>The most complicated situation is when you are dealing with a universal app that needs to maintain compatibility all the way back to iOS 3.1.x or earlier. In this case you will need to use very specific Icon filenames as the Info.plist keys were not used prior to iOS 3.2. The full list would now be something like this:</p>

<ul>
<li>Icon.png - 57x57 iPhone App Icon</li>
<li>Icon@2x.png - 114x114 iPhone retina display App Icon</li>
<li>Icon-72.png - 72x72 iPad App Icon</li>
<li>Icon-72@2x.png  - 144x144 iPad retina display App Icon</li>
<li>Icon-Small.png - 29x29 iPhone settings and search results icon</li>
<li>Icon-Small@2x.png - 58x58 iPhone retina display settings and search results icon</li>
<li>Icon-Small-50.png - 50x50 iPad search results icon</li>
<li>Icon-Small-50@2x.png - 100x100 iPad retina display search results icon</li>
</ul>


<p>Of course there is nothing to stop you using this naming convention for all of your apps but if you are targeting iOS 3.2 or later you can specify different filenames using the Info.plist file. The CFBundleIconFiles key was introduced with iOS 3.2 and allows you to directly list the names of the icon files. if you omit the filename extension (.png) you should be able to omit listing the @2x variants as the system should automatically detect the double resolution versions.</p>

<p>To further complicate things Apple introduced a new CFBundleIcons key in iOS 5.0 to support the Newsstand. This key contains a CFBundleIconFiles subkey which is an array of filenames which take precedence over the older CFBundleIconFiles key. If you are targeting iOS 5.0 and later you can switch to this key but if you need to support iOS 4.x or 3.2 you should also include the CFBundleIconFiles key.</p>

<p>All in all this is a bit of a mess and I would suggest that you test all of the various combinations you need to support carefully as it is easy to slip up.</p>

<h3>App Store Screenshots</h3>

<p>Apple recently changed the App Store submission rules for iPhone and iPod touch apps so that you have to submit screenshots for the retina display. The actual dimensions of the screenshot vary depending on whether you include space for the status bar or not but dimensions should be as follows (first value includes the status bar):</p>

<ul>
<li>Landscape: 960x640 or 960x600 pixels</li>
<li>Portrait: 640x960 to 640x920</li>
</ul>


<p>Apple has not, so far, placed a similar restriction on iPad screenshots but since you will want your screenshots to look good on the latest iPad it seems like a good time to switch to only retina sized screenshots for all devices.</p>

<p>The dimensions for a retina iPad screenshot are as follows (as before the first dimension includes the status bar):</p>

<ul>
<li>Landscape: 2048x1536 or 2048x1496 pixels</li>
<li>Portrait: 1536x2048 or 1536x2008 pixels</li>
</ul>

]]></description>
    </item>
    
    <item>
		  <title>Git branch management with Xcode</title>
		  <link>http://useyourloaf.com/blog/2012/02/29/git-branch-management-with-xcode.html</link>
      <pubDate>Wed, 29 Feb 2012 21:19:00 +0000</pubDate>
		  <guid>http://useyourloaf.com/blog/2012/02/29/git-branch-management-with-xcode.html</guid>
      
        <category>git</category>
      
      <description><![CDATA[<p>Xcode has supported <a href="http://git-scm.com/">Git</a> for version control since version 4.0 but I generally prefer to perform my version control from the command-line. The only version control operation that I do sometimes perform with Xcode is visualising differences between file versions. Xcode does a pretty nice job of showing the two versions of a file side by side and highlighting the additions/deletions in a way that is a lot clearer than a command-line diff.</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-28-000.png" alt="" /></p>

<p>The other version control operation that I suspect could sometimes benefit from some visual tools is the management of branches and in particular the merging of branches. Since Xcode has the ability to manage Git branches I thought I would take a look and share my experiences in this post.</p>

<h3>Creating a Branch</h3>

<p>For the purposes of this post I am going to use my CodeExamples repository and create a new branch to experiment with converting one of the example projects to ARC. The Xcode features for managing branches are (mostly) contained in the Repositories section of the Xcode Organizer.</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-28-001.png" alt="" /></p>

<p>To create a new Git branch from the Xcode organizer you need to make sure that the Branches folder is selected in the left-hand Navigator pane. You should then see the Add Branch and Remove Branch buttons in the command bar at the bottom:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-28-002.png" alt="" /></p>

<p>When you select the Add Branch button you get a dialog box allowing you to name the branch and also to specify from which branch this new branch should be based. Since at this point we only have the master branch we will use that and name the new branch &#8220;ARC-Conversion&#8221;:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-28-003.png" alt="" /></p>

<p>For comparison to create this new branch from the command-line using the branch command:</p>

<pre><code>$ git branch ARC-Conversion
</code></pre>

<p>One thing to be aware of if you are using the command-line is that creating the branch will not also switch you to the new branch.</p>

<h3>Switching branches</h3>

<p>When we created the branch using Xcode we selected the checkbox to switch us to the new branch. The current branch is always displayed in the top right-hand corner of the Organizer window when the project directory is selected in the Navigator pane on the Organizer.</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-28-005.png" alt="" /></p>

<p>To verify the current branch from the terminal use the branch command to list all of the branches. The current branch is indicated by the leading &#8220;*&#8221;:</p>

<pre><code>$ git branch
* ARC-Conversion
  master
</code></pre>

<p>If you want to switch between branches from within Xcode you can do that from the Organizer using the appropriately named &#8220;Switch Branch&#8221; icon in the bottom right corner (again ensure you have the project directory selected in the left-hand pane and not the Branches or Remotes folders):</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-28-004.png" alt="" /></p>

<p>This drops down a dialog box which allows you to select from the available branches. The command-line equivalent using the checkout command to switch to the master branch would be as follows:</p>

<pre><code>$ git checkout master
</code></pre>

<p>To switch back to our feature development branch:</p>

<pre><code>$ git checkout ARC-Conversion
</code></pre>

<p>One thing you need to be aware of if you are performing git version control from the command line with the project open in Xcode is that it does not always immediately spot when you have changed something. I find with the Organizer that you need to switch between some different views before it spots that the current branch has changed.</p>

<h3>Committing Changes</h3>

<p>For the purposes of this example I am going to generate some changes by converting this project to ARC. I will not cover that process and the results here as that is a topic for a separate post, for now it is sufficient that we have some changes to our project that we need to commit. The files that have been changed are visible in the Xcode Navigator pane (marked with &#8220;M&#8221; for modified):</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-28-006.png" alt="" /></p>

<p>You can also of course always check what has changed from the command-line (note that we are on the ARC-Conversion branch):</p>

<pre><code>$ git status
# On branch ARC-Conversion
# Changes not staged for commit:
#   (use "git add &lt;file&gt;..." to update what will be committed)
#   (use "git checkout -- &lt;file&gt;..." to discard changes in working directory)
#
#       modified:   Stepper.xcodeproj/project.pbxproj
#       modified:   Stepper/UYLAppDelegate.m
#       modified:   Stepper/UYLViewController.h
#       modified:   Stepper/UYLViewController.m
#no changes added to commit (use "git add" and/or "git commit -a")
</code></pre>

<p>To commit these changes to our new branch you can either use the Commit button in the Organizer or from the Xcode application menu use File > Source Control > Commit or if you can remember the keyboard shortcut simply type Option-Command-C.</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-28-007.png" alt="" /></p>

<p>The commit window gives you a very nice overview of the files that will be included in this commit so that you can review the changes. If you really want to you can deselect some of the files from the commit, but all you really need to do is enter a commit message (always a good idea) and hit the commit button.</p>

<p>The command-line equivalent would be something like this:</p>

<pre><code>$ git commit -a -m "Converted to ARC"
[ARC-Conversion 7ec268a] Converted to ARC
 4 files changed, 6 insertions(+), 15 deletions(-)
</code></pre>

<h3>Merging Changes Back to Master</h3>

<p>Once you have completed development of the new feature (and of course tested everything) it needs to get merged back into the master branch. To do that you first need to switch back to the Master branch (using Xcode or from the command-line).</p>

<p>At this point things get a little bit confusing with Xcode as to merge the changes you need to switch back to the Xcode project window. There does not seem to be any way to perform the merge from the Xcode Organizer window. With the project window selected you can access the File > Source Control > Merge menu option. I find this a little annoying that the branching and merging commands cannot all be performed from the Organizer. Anyway once you find the Merge command you should see a dialog asking you to confirm which branch you want to merge back into the current (master) branch. Since we only have one branch in this example we just need to choose the ARC-Conversion branch:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-28-008.png" alt="" /></p>

<p>The Merge window looks very similar to the Commit window in that it allows you to view a diff of the changes but also importantly to select which branch to keep in the event that you have a conflict. In a real world situation it is possible that the master branch has also changed whilst we have been working on our great new feature. This may mean you need to keep the changes from one of the branches or maybe merge the two sets of changes manually.</p>

<p>The Xcode Merge window shows you each change along with an indicator showing which change is being preserved. In the screenshot below the master branch is on the left and the ARC-Conversion branch is on the right.</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-28-009.png" alt="" /></p>

<p>The small indicator icon in the middle indicates that the change from the ARC-Conversion branch has been merged into the master branch version of the file. The icons at the bottom of the window allow you to change this and if required discard the change from our feature branch. Of course, you can also manually edit the master file at this point to resolve any conflicts.</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-28-010.png" alt="" /></p>

<p>To merge the branch manually in the situation where the master branch has changes in a file:</p>

<pre><code>$ git merge ARC-ConversionAuto-merging Stepper/Stepper/UYLViewController.m
CONFLICT (content): Merge conflict in Stepper/Stepper/UYLViewController.m
Automatic merge failed; fix conflicts and then commit the result.
</code></pre>

<p>In this case we need to manually fix the conflict in the UYLViewController.m file and then tell git that we have resolved the conflict by adding the file back to the changes to be committed. We can then perform the commit to finish the merge:</p>

<pre><code>$ git add Stepper/Stepper/UYLViewController.m$ git commit 
  -m "Merge of ARC-Conversion branch"
</code></pre>

<h3>Deleting the Branch</h3>

<p>Now that all of the changes have been merged backed into the master branch we can clean up by deleting the feature branch. From the Xcode Repositories Organizer view this is as simple as selecting the branch and then using the Remove Branch icon.</p>

<p>Xcode will complain if you try to delete a branch that it thinks has not been merged. In playing with this feature I found that Xcode would get confused if I needed to manually resolve some conflicts and performed the final merge and commit from the command-line. To get Xcode to delete a branch without complaining it was necessary to perform an additional merge from within Xcode - which of course did nothing as all of the changes had already been merged.</p>

<p>Alternatively to delete the branch from the command-line:</p>

<pre><code>$ git branch -d ARC-Conversion
</code></pre>

<h3>Summary</h3>

<p>In playing with Xcode to perform branches and merges I have to say I really wanted to like the feature. I have always liked the way that Xcode visually displays code diffs and the ability to extend that capability to resolving conflicts during merges seems promising. I am assuming that a few of the minor glitches and bugs will get cleaned up but even so I think I will stick to the command-line for branching and merging. The command-line is always going to be faster once you get the commands stuck in your head and it just feels safer not to have Xcode acting as an intermediary. The visual tools are a nice bonus option to have though.</p>
]]></description>
    </item>
    
    <item>
		  <title>Updating to Xcode 4.3</title>
		  <link>http://useyourloaf.com/blog/2012/02/17/updating-to-xcode-43.html</link>
      <pubDate>Fri, 17 Feb 2012 23:10:00 +0000</pubDate>
		  <guid>http://useyourloaf.com/blog/2012/02/17/updating-to-xcode-43.html</guid>
      
        <category>Xcode</category>
      
      <description><![CDATA[<p>As if all the excitement of <a href="http://www.apple.com/macosx/mountain-lion/">Mountain Lion</a> was not enough for this week Apple has also pushed out Xcode 4.3. The big change is that Xcode is now a standard Mac App Store package which installs directly into the Applications directory. Previously when you installed from the App Store you rather confusingly downloaded an Xcode installer into the Applications directory which you then ran to install Xcode into /Developer.</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-17-001.png" alt="" /></p>

<h3>Installing</h3>

<p>Xcode 4.3 is a free download from the <a href="http://itunes.apple.com/gb/app/xcode/id497799835?mt=12">Mac App Store</a> which, once it has downloaded, will install directly into the /Applications directory. You no longer even get an installation dialog offering you a choice of the installation directory though I guess there is nothing to stop you from moving it later. (Note that if you are developing for the iOS 5.1 beta release you should continue to use the Xcode 4.3 Developer preview available from the iOS Dev Center.)</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-17-002.png" alt="" /></p>

<p>Once the download is complete you should find Xcode installed in your /Applications folder just like any other App Store application. When you run Xcode for the first time you are prompted to remove the old version of Xcode that is in installed in /Developer (version 4.2.1 in my case) and also to delete the now redundant Xcode installer from /Applications:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-17-003.png" alt="" /></p>

<p>Of course if you want to maintain the older version for a while you are not forced to delete it right now you just need to manually drag the relevant files to the trash when you are ready.</p>

<p>As we have <a href="http://useyourloaf.com/blog/2012/01/10/xcode-42-building-for-ios-31x-and-older-devices.html">previously seen with Xcode 4.2</a> you need to download some optional components from the preferences if you want the iOS 4.3 Simulator or device debugging support for iOS versions prior to iOS 4.3. What has changed with Xcode 4.3 is that even the command-line tools are now an optional download:</p>

<p><img src="http://useyourloaf.com/assets/images/2012/2012-02-17-004.png" alt="" /></p>

<p>The interesting thing about the command line tools being a separate download is that it means they can now be installed without Xcode making life easier if you just want the compiler or OS X header files. The download link for the command line tools and a number of other optional tools that are now no longer bundled with Xcode can be found on the <a href="https://developer.apple.com/downloads/index.action?name=for%20Xcode%20-">Apple developer site</a>.</p>

<h3>/Developer Be Gone</h3>

<p>It is somewhat odd to be developing on a Mac that does not have a /Developer directory. One immediate impact of this will be on any scripts you have that rely on command-line tools that previously lived in /Developer. For example I often used the agvtool to <a href="http://useyourloaf.com/blog/2010/08/18/setting-iphone-application-build-versions.html">manage build version numbers</a> but if you try to run it after installing Xcode 4.3 you will get the following error message:</p>

<pre><code>$ agvtool
Error: No developer directory found at /Developer.
Run /usr/bin/xcode-select to update the developer directory path.
</code></pre>

<p>The xcode-select utility allows you to switch between versions of Xcode which makes it easy to correct the problem:</p>

<pre><code>$ sudo /usr/bin/xcode-select -switch /Applications/Xcode.app
</code></pre>

<p>If you are wondering where all of the files that were previously under /Developer have gone you can find them by right-clicking on the Xcode.app file in the Applications folder and showing the package contents. The old /Developer/usr/bin directory is now in /Applications/Xcode.app/Contents/Developer/usr/bin.</p>

<p>Don&#8217;t forget to clean up your shell environment if you previously referred to anything under /Developer. So for example, if you added /Developer/usr/bin to your PATH and /Developer/usr/share/man to your MANPATH you will need to prepend /Applications/Xcode.app/Contents to these settings in your shell login script.</p>

<h3>Where Did Instruments Go?</h3>

<p>One other side-effect of this reorganisation is that you can now no longer navigate with the Finder under /Developer to access some of the additional developer tools such as Instruments. To get around this you can launch them from the Xcode > Open Developer Tool menu or alternatively you will also find them by right-clicking on the Xcode icon in the dock. Of course, you can use Options > Keep in Dock from the dock icon of the running application if you want to keep the icon handy in the dock for future access.</p>
]]></description>
    </item>
    
  </channel>
</rss>
