tag:blogger.com,1999:blog-58635488742989583432024-03-27T07:37:42.972+01:00iOS Development: You're Doing It WrongHow to do things The Right Way™ when it comes to iOS Development.Unknownnoreply@blogger.comBlogger6125tag:blogger.com,1999:blog-5863548874298958343.post-87352763939214511022013-06-28T12:38:00.001+02:002014-05-15T19:59:38.099+02:00iOS App Architecture and TDD #1: The UIViewController Spaghetti Monster<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqBI9YuUotB03XAo-PFZAyk0eFM_hF9QWc4thbmnuqvPT5hIO-VikcNsjAjNqe1FTxsGJ99WOO6CZMaP6337u5c4o3H7BrO_DjVRo9RxXr0CMYArb8mVPgIgz6NkassXlg-uqsLeIa1RJ-/s813/frame1.jpg" alt="We made it, Trinity." />
</div>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijg58Y_UIU4IcPGaKZ58r4PpDICF3vmIQJj-hJ1Oc-BgHikmvdhRqcVsVCROG08cefqREEVuI4ziA5KDeiGdGDfvAtRSTqHQwAJ42hnssJkLCz91jN61aTB0b9zXjNVYwjTScxGW1U91d7/s815/frame2.jpg" alt="You said we would." />
</div>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfJteSAzjw7yB-Na_Lrf_eAiV7C5dVuVVDR-jAuC2PJ4laFbjj3lfeirf3yN6FGb3tMnnVJ6QBMS-IQZJ-JUhE4F-KdMJDdSc2E1W5K7Xz6xo6JBeDBNgfi-33dfQOYdxrRfAcsbAuIcjx/s816/frame3.jpg" alt="It's unbelievable Trin..." />
</div>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjeKm4aXleSCREFvYYMcL3qBXXJ_B7BcW6ToKJFaY0-jczVUC8uM6CejGGVpmTDGWg3n5r9KwYyVztvY91zk_FqymRHh9Q9Q0uWvvu5CW1-3i043wPAsQyyryCPna2IBbMYKPqHEIy00XQ/s815/frame4.jpg" alt="We finally made another blog post." />
</div>
<h2>Agenda</h2>
<p>I want to talk about iOS app architecture and Test Driven Development.</p>
<p>For the past couple of years I’ve been developing the feeling that there’s something seriously <em>wrong</em> with how a lot of people are approaching iOS development. Apple has made certain decisions with their framework design and tools which I believe contributes to this problem.</p>
<p>Specifically I’m talking about where the application and business logic for an app belongs, and how the overall architecture of an app should be constructed. I feel I need to slap some people across the face and bring them to their senses (including myself).</p>
<p>This is going to be the first in a series of posts. Today we’re going to find out why Apple has created a total abomination of design with <code class="prettyprint">UIViewController</code>. Should be fun.</p>
<p>In future posts I will describe an Uncle Bob style “Clean Architecture” for iOS apps, driven by TDD. I haven’t seen anything like this from other writers/developers, so be sure to subscribe (or follow me on twitter) if that sounds interesting.</p>
<h2>The Humble View Controller?</h2>
<p>Way back in 2002, Michael Feathers (of “Working Effectively with Legacy Code” fame) wrote a piece titled <a href="http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf"><em>The Humble Dialog Box</em></a>. In it, he describes a particular approach to separating GUI-specific code from the actual application logic behind a simple dialog box.</p>
<p>We’ll revisit this piece sometime in the future, but for now I want to focus on the introductory problems he describes. Remember he is talking about building desktop applications here:</p>
<blockquote>
<p>Let’s take a look at our friend the dialog box. […]</p>
<p>Tool vendors have made it easy to create dialog boxes. Nearly every IDE on the market has a GUI builder. You can drag and drop all sorts of components on dialogs and drill down to wire them up. […]</p>
<p>It is easy to just override an event from a component and drop your interaction logic right there in the dialog box class. </p>
</blockquote>
<p>He goes on to describe the problems that typically arise with these dialog box classes:</p>
<ul>
<li>It’s difficult to get these UI classes under a test harness because they are so tied to UI-specific frameworks. There is no separation between the UI and interaction/application logic.</li>
<li>The UI classes have a mixture of low level component API code as well as actual decision making code, making it hard to see what the code is doing or to share code between objects with similar behaviour.</li>
</ul>
<p>These statements perfectly describe a typical iOS view controller. It’s easy to drop code into an <code class="prettyprint">IBAction</code> method or a delegate call on the view controller, and do everything right there and then. This can lead to a mixture of “component API” (i.e. UIKit) and important decision making code.</p>
<p>Apple has made <code class="prettyprint">UIViewController</code> the center of the iOS universe. When you add a new screen to your app, the only thing that Xcode gives you is a new <code class="prettyprint">UIViewController</code> subclass. And Apple makes it <em>so</em> easy to do everything from this view controller. If you aren’t really careful, you can end up with an application consisting entirely of view controller classes and little else.</p>
<div class="centered-image-container">
<a href="https://twitter.com/Colin_Campbell/status/293167951132098560"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiA6otWLYG5HTx0iu4XdCib8YVK2h8ZrD3PHzQghpkLbHpH-vaS1_7KFMQSFGz0X8z7XYMBNqZSBNqiCR2w4V9Nb99AS-XEMi25_wExhpMzX7I5USdg_ehtqLu6O3A-zKDmf4vcG7mAHyPK/s473/MassiveViewControllerTweet.png" alt=""iOS architecture, where MVC stands for Massive View Controller"" /></a>
</div>
<p>Now of course there are good developers out there who are creating nicely decoupled classes, but if we list out some of the responsibilities that a view controller typically ends up dealing with, we’ll see just how pervasive this problem is, even in code written by experienced developers.</p>
<h2>Spotted in the wild</h2>
<h3>View setup and layout code</h3>
<p>By default, when you hook up a new control to your view controller’s XIB or storyboard (for example a <code class="prettyprint">UIButton</code> or <code class="prettyprint">UILabel</code>), the IBOutlet connection is going to go to a property on your view controller. The whole assistant-editor workflow is designed to do this. All of the sample code, tutorials and books you will ever read will do this as well.</p>
<p>If you need to tweak that control’s settings in code, your first stop will probably be the trusty <code class="prettyprint">-viewDidLoad</code> method:</p>
<div class="code">
<pre class="prettyprint">
- (void)viewDidLoad
{
[super viewDidLoad];
self.myButton.titleLabel.font = myCustomFont;
UIImage *stretchableImage = /* ... blurgh ... */
[self.myButton setBackgroundImage:stretchableImage
forControlState:UIControlStateNormal];
/* ... more 'blurgh' ... */
}
</pre>
</div>
<p>Over time, your <code class="prettyprint">-viewDidLoad</code> will likely grow. You may even create new controls in here that don’t exist in your XIB file. Even if you break things out into multiple methods, a significant part of your view controller’s code can end up dealing with view setup and creation. The situation is worse if you forgo XIB files entirely.</p>
<p>And what if you have custom layout requirements which can’t be solved in IB?</p>
<p>Well… you <em>could</em> create a <code class="prettyprint">UIView</code> subclass and implement <code class="prettyprint">-layoutSubviews</code>. But you already have all your IBOutlets going to the view controller. You would have to move all the IBOutlet connections and properties to this new view class — and why bother with all that when it’s so easy to add some code to <code class="prettyprint">-viewWillAppear:</code>:</p>
<div class="code">
<pre class="prettyprint">
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.myLabel.frame = /* ... */
self.myButton.frame = /* ... */
}
</pre>
</div>
<p>Even though using a <code class="prettyprint">UIView</code> subclass and overriding <code class="prettyprint">-layoutSubviews</code> is a far superior way to layout your controls (and is in fact <em>the</em> correct way), people end up putting this stuff in their view controllers because that’s the easiest thing to do.</p>
<p>And then they have to deal with view rotation issues, and not being told when the view’s frame changes. Even worse, because this stuff is so hard to do properly from the view controller, people often end up hard coding interface sizes and frames rather than implementing truly dynamic view layouts.</p>
<p>I’ve seen people doing layout in the <code class="prettyprint">-viewDidLoad</code> method, before the view is even part of the view hierarchy. And they wonder why things mess up. You can’t even blame them. After all, it is Apple who is encouraging people to connect their IBOutlets to the view controller.</p>
<p>It all becomes a hideous mess, and could easily be solved with <code class="prettyprint">UIView</code> subclasses. But Apple doesn’t teach us to do this. I doubt many novice or intermediate iOS developers have even heard of <code class="prettyprint">-layoutSubviews</code> or <code class="prettyprint">-sizeThatFits:</code>. All Apple gives us by default is a view controller subclass.</p>
<p>Even with Autolayout the problem doesn’t go away. The view controller still ends up being the place to create custom constraints, for the same reasons as above. That’s just how people do it. Even Apple engineers do it this way in their WWDC videos.</p>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhS6tAveeKscrBKwM01Bsh1K8atYTcyhMlTnALUBCdadnq4ASTQh1QqWO_KEJgxlKiUZe3-Xp04W6Bfp_LFTnSHCyXrD-6tPTCeer9NRa4tOdg-ToUVNugCMbymS7S3PN_K6thld0DArcVz/s914/wwdc_viewdidload_constraints.png" alt="Apple engineers teaching us bad habits." style="max-width: 100%;" />
</div>
<p>So the Xcode/Apple-approved default is to have all of your view setup and layout code in the view controller. Why is this a bad thing? Quite simply, because view layout and setup code should (in my opinion) always go in <code class="prettyprint">UIView</code> subclasses. That’s where it belongs, and life is a lot easier when you do it this way. Putting this stuff in the view controller is just contributing to an already bloated and confused class.</p>
<h3>Core Data and <code class="prettyprint">NSFetchedResultsController</code> code</h3>
<p>All of the Core Data sample code that I’ve seen from Apple creates and sets up the <code class="prettyprint">NSFetchedResultsController</code> in a <code class="prettyprint">-fetchedResultsController</code> method on the view controller. It’s usually a huge long method which sets up the fetch request, configures the <code class="prettyprint">fetchBatchSize</code>, predicate, sort descriptors etc. </p>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiONz_3YHvlmCvj7I0G1vHKErKzTho5Foa6c3yuONR8rmcOU6T4nhNbO0FxIG7lxkO5TEazizxw5gqS0q74arS5eUse4tlBKsxuAXql-ELqmeT25LPF11iolD0QwTBJ97igw3H1c-yGdDnv/s578/fetchedResultsControllerMethod.png" alt="Xcode screenshot showing Apple's CoreDataBooks sample project creating and setting up the fetched results controller in the view controller." />
</div>
<p>Unfortunately I’ve seen a lot of people who have copy/pasted this kind of code into their view controllers. As time goes on, the view controller ends up with a dozen methods just dealing with Core Data - fetching results, updating records, performing background operations, merging contexts, etc.</p>
<p>None of this stuff belongs in the view controller. You have business logic like sorting and filtering rules mixed in with the details of the persistence framework (Core Data), and all of this inside the view controller. A “view controller” should not be dealing with this stuff, and Apple unfortunately does not show new-comers how to do this properly.</p>
<h3>Be the delegate for everything</h3>
<p>Even if you pull your Core Data code out into a nice class or interface, your view controller will probably end up being the delegate and datasource for the table view displaying that data. It’ll contain the code to create and configure table view cells for a given item, define section titles and row heights, handle insertion and deletion operations, and respond to any of the dozen or more delegate/datasource callbacks that are available.</p>
<p>If your app is making use of <code class="prettyprint">CLLocationManager</code>, your view controller will probably end up responding to and handling location events. It might even be the one that creates the location manager in the first place. Another of Apple’s tutorials does just this.</p>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhA174cv7IWQHxxaLWv151eALqlmQKHBYwP4SS76Jdb8KFVNCX3lVlTu4KS8yshBG1bPOvIDWgTVWHy6BumVoWd9TSl1gIr1BHqZ0ZeCOHwxQRyfDCJL9-t7680BM0WJj5YJ_3SWUPZyLVV/s647/CLLocationManager.png" alt="" />
</div>
<p>If your view controller makes use of <code class="prettyprint">MPMoviePlayerController</code> or <code class="prettyprint">QLPreviewController</code> or <code class="prettyprint">MFMailComposeViewController</code> you’ll probably be the delegate for those as well. You can also throw in Twitter and Facebook API callbacks (and sharing in general), quick one-off <code class="prettyprint">AFNetworking</code> or <code class="prettyprint">NSURLConnection</code> web service requests, <code class="prettyprint">NSTimer</code>s doing periodic background work, <code class="prettyprint">SCNetworkReachability</code> checks, and the list goes on.</p>
<p>Because <code class="prettyprint">UIViewController</code>s are such a central part of an iOS app, they end up being the delegate for <em>everything</em>. They end up accumulating all this <em>crap</em>. If the view controller was purely forwarding information and acting as an intermediary, this might not be so bad. But we all know that’s rarely the case.</p>
<p>You really have to be on the ball to keep this stuff nicely separated, and I’ve seen a lot of codebases which fail to do this.</p>
<h3>Accessing global state</h3>
<p>Because it’s so easy to drop code into a view controller, and because Xcode doesn’t give you any other place to start adding your code, inexperienced developers have trouble accessing the information they need.</p>
<p>They end up using hideous hacks like <code class="prettyprint">((IHaveNoIdeaWhatImDoing*)[[UIApplication sharedApplicaton] delegate]).objectThatINeed</code>, or singletons, or notifications, to access everything they need. Stackoverflow and internet forums get inundated with questions of the form “How to I pass information from one view controller to another”?</p>
<p>The reason this is so difficult is that they haven’t been taught to write higher-level objects which deal with the interactions and flow of information in their app.</p>
<p>So not only do many view controllers have dozens of delegate calls coming <em>in</em> to them, they also have hideous clawed tentacles reaching <em>out</em> all over the application, accessing global state and further coupling the view controller to other parts of the application.</p>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRGIC8QYkeb_L3PL-Jd-fY_pkpfoVd6UE21bRB2ttreTzjoW3zgwIFu1Yq6j9EY02dQynpYH0mugN6NrzbvaJgnukxO-pdg7zqEYoBWFi2olWXle20a54qmv0BWGXaqIJSnYwhmFJx7L2V/s540/Tentacle1.jpg" alt="Some people have tried to contain the UIViewController..." style="max-width:100%;" />
</div>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCrVI5J2Fb1socNYxI5xScIal5n5XVGl7Uue6nPAOZfPIr5oLrxtU2kmTT6QH_3CjJhVtlyqotwXCb6tEEUWEvsyEnheJyFbkJWmJffOWAm6o1beBs33Xtj-nl6Kq49T52e5z6j9wWAOaH/s500/Tentacle2.jpg" alt="This usually doesn't end well." style="max-width:100%;" />
</div>
<p>You can argue that this is just a problem of inexperienced developers, but Apple really does not help people to develop good coding practices. I’ve seen Apple sample code using <code class="prettyprint">[[UIApplication sharedApplicaton] delegate]</code> to access global state, and it’s really a terrible practice to encourage. In fact I already have a blog post half-written which deals precisely with this topic.</p>
<h3>Navigation logic and other “decision making” code</h3>
<p>When the user selects a cell from your table view, you are going to handle the <code class="prettyprint">tableView:didSelectRowAtIndexPath:</code> method.</p>
<p>Your app now has to decide what to do. In a typical drill-down style of navigation, you want to push some sort of “details” screen for the selected item.</p>
<p>Apple makes this really easy with convenience methods on <code class="prettyprint">UIViewController</code> like <code class="prettyprint">-navigationController</code>, <code class="prettyprint">-tabBarController</code>, <code class="prettyprint">-splitViewController</code>, etc. Your view controller can directly grab a reference to the container that holds it.</p>
<p>You can then do something like this:</p>
<div class="code">
<pre class="prettyprint">
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
id item = [self itemAtIndexPath:indexPath];
DetailsViewController *detailsVC
= [[DetailsViewController alloc] initWithItem:item];
[self.navigationController pushViewController:detailsVC
animated:YES];
}
</pre>
</div>
<p>Perfect! The navigation logic can be dropped <em>right there</em> in the view controller!</p>
<p>But what if you later make your app universal, and the details screen needs to appear in a split view controller on iPad devices?</p>
<p>Well, no problem. We’ll add a little runtime check:</p>
<div class="code">
<pre class="prettyprint">
DetailsViewController *detailsVC = /* ... */;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// display details in the split view controller's details pane
} else {
// push details to the current navigation controller
}
</pre>
</div>
<p>We also need to keep the cell selected on the iPad, but deselect it in <code>viewWillAppear:</code> on iPhone devices (this is what <code class="prettyprint">UITableViewController</code> does by default). This adds a few more if statements to the controller.</p>
<p>But what if you now want to present this view controller modally at some point in your application so the user can select one item for a task? In that case you need to dismiss the view controller and somehow notify the parent about which item was selected.</p>
<p>We can’t keep adding more and more if statements to our view controller. It’s pretty clear that this kind of navigation logic doesn’t belong in the view controller.</p>
<p>A view controller should not know about the high level work flow of your app. It shouldn’t know about its surroundings. It shouldn’t know that it’s being presented modally, or that it’s contained by a navigation controller, or a split view controller, or a tab bar controller. It shouldn’t even have references to these things, even though Apple decided to “help” us out by tacking on all these category methods. It shouldn’t even know about the <code class="prettyprint">DetailsViewController</code>. That’s an entirely different screen of our app.</p>
<p>If our view controller is displaying a list of items (think a typical table view controller), that’s all it should be concerned with. It should provide some delegate callbacks for when a given cell or item is selected, and perhaps a few ways to customize the display or behaviour of the cells, for example to enable a check-multiple-items style of selection.</p>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjRXxLgSE3VUwh5EE7S2F4MYLpf92VAHgBhSUumk7mrqm_HGbTUQY1Lcfta2q8loWsxXjvB0zdRVC838lCvQnpS_upGCHea64VMJz7EQCrts0nsW7YzHH-lolbOQ9KrZ7esy9JwiwaO7FJA/s672/different_navigation_items.png" alt="The same view controller being presented in different contexts, with different navigation items." style="max-width: 100%;" />
</div>
<p>The view controller should only be concerned with the behaviour of the view that it presents. By putting navigation logic in the view controller, you are coupling it to the specifics of your app’s UI and navigation. If you want to change the workflow later (e.g. for other devices), or reuse that view controller in a different context (or even a different app), you are going to encounter a lot of pain.</p>
<p>So where should this navigation logic go? Well… somewhere else. We’ll get into that in a later post. All that matters for now is that the view controller should delegate UI actions like this to somebody at a higher level, who has access to and knowledge of the specifics of your app’s UI workflow.</p>
<p>This is also why I have a big problem with Storyboards. When you implement a Storyboard app, you are forced to put application-specific navigation logic in the view controllers by implementing the various <code class="prettyprint">UIViewController</code> segue-related methods. There’s no other way to do it. And delegating this stuff out to somewhere else really confuses the matter because you have this extra level of indirection between the storyboard XIB and the segue code. Reusing view controllers in other apps or screens suddenly becomes impossible to do (or at least very difficult) without creating a total mess of things.</p>
<h2>Official UIKit responsibilities</h2>
<p>So far we’ve mostly looked at logic and code that could theoretically be pulled out of the view controller and put somewhere else. You’ll probably be doing this already to a greater or lesser extent.</p>
<p>But what about the stuff that a <code class="prettyprint">UIViewController</code> <em>must</em> deal with? What about it’s official UIKit responsibilities?</p>
<p>In fact, what the hell <em>is</em> a “view controller” anyway? Does anybody actually know? Why do we now have view controller containment hierarchies as well as regular view hierarchies? How does it differ from a <code class="prettyprint">UIView</code> in this case? What does this all have to do with MVC?</p>
<h3>What is a view controller?</h3>
<p>To figure this out, we are going to start pulling code <em>out</em> of some hypothetical view controller and see what’s left at the end.</p>
<p>First we’ll move all that horrible view setup and layout code into a <code class="prettyprint">UIView</code> subclass. <em>Done</em>.</p>
<p>Then we’ll move all the core data and model code into some nice protocols/classes, which are injected into the view controller through public properties or an <code>-init</code> method. <em>Done</em>.</p>
<p>We’ll move the table view delegate/datasource code into dedicated classes. <em>Done</em>.</p>
<p>Any miscellaneous framework code, url requests, etc. will also be pulled out behind nice interfaces, and our view controller will simply funnel data back and forth between the view and these interfaces. <em>Done</em>.</p>
<p>Finally, let’s delegate navigation events like certain button presses and cell taps to somebody else, so the view controller’s behaviour can be customized easily for use in different contexts. <em>Done</em>.</p>
<p>What are we left with at the end of all this?</p>
<p>We’re left with a class that:</p>
<ul>
<li>Lazily loads a view (by calling <code class="prettyprint">-loadView</code> when the <code class="prettyprint">-view</code> property is accessed for the first time)</li>
<li>Can load its view from a NIB file in a convenient manner.</li>
<li>Provides access to various events like <code class="prettyprint">-viewDidAppear:</code>, <code class="prettyprint">-didRotateFromInterfaceOrientation:</code>, and <code class="prettyprint">-didReceiveMemoryWarning</code>.</li>
<li>Deals with state restoration to restore state between launches of your application.</li>
<li>Handles storyboard segues to pass data to the view controller that is being transitioned to.</li>
<li>Can provide accessibility information about the content it displays.</li>
<li>Allows you to define which interface orientations are allowed when its view is at the top of the view hierarchy.</li>
<li>Can be inserted into UIKit’s standard containers like <code class="prettyprint">UINavigationController</code> and <code class="prettyprint">UITabBarController</code> (also <code class="prettyprint">UIWindow</code>), with a bunch of properties like <code class="prettyprint">navigationItem</code> and <code class="prettyprint">tabBarItem</code> to customise its appearance in these.</li>
<li>Can be nested inside another view controller in a UIKit-safe way.</li>
<li>Happens to be part of the responder chain, so can respond to and handle certain types of input events.</li>
</ul>
<p>Wow. That’s a lot of stuff, and I’ve probably forgotten some things. It also sounds a hell of a lot like a view to me. The lines are starting to blur. It certainly doesn’t sound like a place for important business or application logic.</p>
<p>If you look at the actual interface for <code class="prettyprint">UIViewController</code> — the methods and properties it declares, it’s almost all view/presentation related. Go on, pop open <a href="http://kapeli.com/dash">Dash</a> and take a look right now. I can only count 5 methods out of 86 that are not presentation related. These are <code class="prettyprint">-didReceiveMemoryWarning</code> and the 4 state restoration methods that came with iOS 6. <em>Everything else</em> is related to the view. And that’s not even including all the category methods that get added on by other UIKit headers.</p>
<h3>An identity crisis</h3>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFSEaiGde0j4FmCPlQ51NrscW1lhBTp-jm2qVaY2plbN-mYzQ0nShranJOkOtEkoHxmmNMlMIIohncrozDEgcGclVeCB3LaZQPdkZuPBy3fij71_CsLwgMhslrbraJ_GwmRYyqEkKhgYPc/s292/identity_unknown.jpg" alt="Who *are* you, UIViewController?" />
</div>
<p>What if we continue to pull stuff out of <code class="prettyprint">UIViewController</code>?</p>
<p><code class="prettyprint">-viewDidAppear:</code> and all the other view-related events would be much happier sitting on the <code class="prettyprint">UIView</code> class instead, for instance.</p>
<p>Lazy loading also seems to be a detail that belongs elsewhere. Don’t we just want something like this?</p>
<div class="code">
<pre class="prettyprint">
UILazyLoadedView *lazy = [[UILazyLoadedView alloc]
initWithLoadViewBlock:^{
MyView *v = [[MyView alloc] init];
// restore view state
return v;
}];
</pre>
</div>
<p>Then we just change the <code class="prettyprint">UINavigationController</code> and other container classes to accept a <code class="prettyprint">UILazyLoadedView</code> where applicable. When our view needs to be displayed or loaded, UIKit can invoke the block and get a view returned to it. Any view state can be captured/restored in the block, making it work well when the view is unloaded/reloaded (prior to iOS 6 anyway).</p>
<p>Let’s look at the <code class="prettyprint">navigationItem</code>/<code class="prettyprint">tabBarItem</code>/etc. properties now.</p>
<p>These properties are used to customise the way the view controller appears in navigation controllers, tab bar controllers, etc. These customizations are always going to vary depending on the context in which the view controller is presented.</p>
<p>So do these properties really belong on the view controller? They’re actually part of the interfaces for the various container controllers that Apple gives us. But they’ve been “helpfully” tacked on to <code class="prettyprint">UIViewController</code> via categories. Is this really a good idea? Didn’t we already establish that a view controller should only know about the content <em>it</em> displays and manages?</p>
<p>If a view controller represents a screen of your app, why does it need to know the title of its back button when another screen is being displayed? Why does it need to have access to the icon image in its tab bar button? Shouldn’t that be managed by the class that set up the tab bar controller, or that pushed it onto the navigation controller?</p>
<p>When we consider the multitude of responsibilities a view controller already has, does it really need to deal with the specifics of all these container controllers as well?</p>
<p>Couldn’t we remove these category methods entirely and provide the information when we do the actual push? Something like this:</p>
<div class="code">
<pre class="prettyprint">
UILazyLoadedView *lazyView = /*...*/;
UINavigationControllerItem *item = [[UINavigationControllerItem alloc]
initWithLazyView:lazyView
title:NSLocalizedString(@"foobar", nil)
backButtonTitle:/*...*/
/* etc */];
[navController pushItem:item];
</pre>
</div>
<p>I don’t know. We’re getting dangerously close to the realm of pure fantasy here. But we need to think about these things to figure out exactly <em>what</em> a view controller is, and what it’s main roles should be. Everything we’ve seen so far seems to belong somewhere else.</p>
<p>The other thing view controllers can do is “view controller containment”. This can only be described as a complete (and unnecessary) mess.</p>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhy3EJdBQvHrfTk7mSo7pXrIeZP_5B1tEZJiv49eTNOKTBZhT-0SlAi0O-eelQmG09xaTzEivv659P2nWmWJ9OJzNYqbVHK5HWz_xB62OpqxYIKJRxa-MycwtiLbxLKnjunEg1kialsm1E9/s667/view_controller_containment_video.png" alt="" style="max-width: 100%;" />
</div>
<p>Because a view controller is just a wrapper around a view, people ended up needing to nest or compose view controller views in a single screen. But things like rotation events, <code class="prettyprint">-viewDidAppear:</code> etc. get all screwed up if you do this by manipulating the view hierarchy directly. This wouldn’t even be a problem if these methods were part of <code class="prettyprint">UIView</code> instead.</p>
<p>So to make this work nicely, Apple has given us the view controller containment APIs, with weird-ass requirements in the order you call the various <code class="prettyprint">willMoveToViewController/didMoveToViewController/addChildViewController/etc.</code> methods.</p>
<p>And now that we have this view controller containment, a view controller no longer represents an entire screen of content. It represents a <em>portion</em> of the screen and can be nested arbitrarily with other view controllers. So… doesn’t that just make it a view? A view with some additional UIKit details hacked on?</p>
<p>Somehow this all feels like a big mess to me. I’ve only covered a few items from <code class="prettyprint">UIViewController</code>’s interface, but it’s already starting to look like this weird “miscellaneous crap that UIKit needs” class with a lazy loaded view inside it. It’s a confused mess of responsibilities.</p>
<p>It also happens to contain the majority of our application code. This is a problem.</p>
<h2>A black hole of bad design.</h2>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjz0jlGnvTfP5J7H5iyt5S51Ks7V3FSiqHMk6G5PY_xsbjKSWAEjW_QLRGNSLXGxo4WVKoMJtf2u0P0Y8yX9Nn08SVCR52FzzHg5QXGwF7IxX3OJZImuNOzFMBpORSHd7bCRQmuXKnr4Zvz/s600/black-hole-swallows-star2.jpg" />
</div>
<p>Let’s summarise the key points so far.</p>
<p><code class="prettyprint">UIViewController</code> is the centre of the iOS world. Apple’s tools like Xcode and Interface Builder, and the workflow they encourage, put the view controller at the centre of everything. The default place to start when you’re adding new code or features is the view controller. When you add a new screen to your app, all you’re given is a <code class="prettyprint">UIViewController</code> subclass and a lot of helpful methods to shoot yourself in the foot.</p>
<p>Because of this, code and logic tend to gravitate towards the view controller. The view controller ends up being the delegate for a large number of different objects. It ends up doing view setup and layout, it ends up dealing with core data, table view datasource/delegate methods, and a huge number of other responsibilities.</p>
<p>Apple has tacked on a large number of “convenience” methods which let you directly access the enclosing containers like navigation controllers or tab bar controllers. This makes it very easy to couple the view controller to the specifics of your app’s navigation, and to the other view controllers it interacts with. Storyboards also contribute to this problem. This makes it difficult to reuse the view controller in other contexts or applications.</p>
<p>Even if you manage to keep your own interfaces/APIs nicely decoupled and separated into other classes, <code class="prettyprint">UIViewController</code> is the only place to deal with certain UIKit details, like: lazy-loading of views, configuring the display of tab bar items and navigation controller elements, view events like <code class="prettyprint">viewDidAppear</code>, rotation events, and view controller containment when you need to nest multiple view controllers inside one another.</p>
<p>If you have any kind of decision making logic in your view controller, it is completely coupled to the UIKit framework. As we’ll see in my next post, trying to get these things into a test harness is a disaster waiting to happen.</p>
<p><code class="prettyprint">UIViewController</code> is just a detail of UIKit’s implementation. It’s more of a view than a controller, and certainly isn’t anywhere close to being a Controller in the classical MVC sense, despite what Apple tries to tell us:</p>
<div class="centered-image-container">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJV-tXGarjpc-INGg2RuPi4Xv2MGcj8Va6sQNVw207_scFhLBR8vMk74j6B-rUV2XbzBtE3ngQCNvVa2_V3LXmkhGw4DkP4egTFGyOtai4SBt9ebSFY_G0L9zSYmUrtH0DtHDGQkHJ3G1a/s732/just_controllers.png" style="max-width: 100%;" alt="WWDC Slide: View controllers are just controllers - the "C" in MVC." />
</div>
<p>“Controllers” are supposed to be nice thin objects funnelling data and events between the model and the view. They shouldn’t contain details of a specific UI framework. iOS’ View controllers are <em>nothing</em> like this. They sit firmly in the presentation layer.</p>
<p>So why are we putting so much of our important application and workflow logic into our view controllers? I feel like the iOS developer community has forgotten everything we have learnt about good OOP design in the last 20 years or so. Remember the Single Responsibility Principle? One Reason To Change? Mixing application logic in amongst the spaghetti of UIKit APIs is just plain <em>wrong</em>.</p>
<p>Isn’t there a better way? Isn’t there an escape from this madness?</p>
<p>I’m happy to tell you that there <em>is</em> a better way.</p>
<p>I’m going to take you on a journey, Dear Reader. A journey of self-discovery and enlightenment. Or… something like that. We’ll figure it out as we go.</p>
<p>We’re going to develop a Clean iOS Architecture together, driven by TDD. We’re going to find out why so many people are doing iOS TDD wrong, and how to do it <em>right</em>. And we’re going to see some really nice benefits from this new approach.</p>
<p>Won’t you join me?</p>
<hr />
<p><em>PS: I’m currently looking for new job opportunities, preferably in the UK. London would be ideal. Please contact me using the email address at the top of this page if you have any offers.</em></p>Unknownnoreply@blogger.com206tag:blogger.com,1999:blog-5863548874298958343.post-1011616380676631742012-08-10T22:14:00.001+02:002012-08-10T22:14:57.983+02:00You're Doing It Wrong #4: -[UIView viewWithTag:]<p><code class="prettyprint">UIView</code> has a <code>tag</code> property and a corresponding <code>-viewWithTag:</code> method. Used together, one can quickly access a specific subview without the need for an explicit property to reference that view.</p>
<p>I’ve seen <code>UIView</code>’s tag functionality abused in many strange and wonderful ways; so much so that I currently believe it best to avoid completely.</p>
<h2>Do not use tags to store data</h2>
<p>Let’s start with a ground rule:</p>
<blockquote>
<p><code>UIView</code>’s <code>tag</code> property should <em>only</em> be used as a unique identifier for a view. It should <em>not</em> store any more information than this.</p>
</blockquote>
<p>Seems reasonable doesn’t it? And yet I’ve seen many developers abusing tags to store additional information, such as array indices pointing to model objects:</p>
<div class="code">
<pre class="prettyprint">
- (void)configureThumbnailButton:(UIButton *)thumbnailButton
forPhoto:(NSUInteger)photoIndex
{
// ...
thumbnailButton.<span class="highlight">tag = 1 + photoIndex</span>;
// ...
}
- (void)thumbnailButtonTapped:(id)sender
{
UIButton *thumbnailButton = sender;
NSUInteger <span class="highlight">photoIndex = thumbnailButton.tag - 1</span>;
id selectedPhoto = [self.photoArray objectAtIndex:photoIndex];
[self showPhoto:selectedPhoto];
}
</pre>
</div>
<p>This example is setting up a button which displays a thumbnail for a photo. When the user taps the button, the corresponding photo is displayed.</p>
<p>To remember which photo should be displayed when the button is tapped, the <code>tag</code> property is given a value based on the array index of the photo. It’s common to see a magic number (1 in this case) added to the tag value to disambiguate between views with the default tag value of 0 and a genuine array index.</p>
<p>Using tags like this is pretty nasty. Although I’ve tried to make the above example as clear as possible for demonstration purposes, code that uses tags in this way is often very difficult to follow because there are no useful variable names anywhere.</p>
<p>Let’s take a look at some real-world examples:</p>
<div class="code">
<pre class="prettyprint">
[pageScroller scrollRectToVisible:CGRectMake(1024 * (sender.tag - 101),
0,
1024,
pageScroller.height)
animated:YES];
</pre>
</div>
<p>Another?</p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe1jj1k7aIjfWPXYNHzIZYBiVQ4X8mhw6M05J0Wt_iM2BU6Ei_heoRZReSn_RqcRXpdrczXWoshggUjftssfbkztLU33N1Bx21tCh78_tqnAfyAgIMpD_qObIp2Sw2lgZ2ILSu-TV7DqZL/s400/joker2.png" alt="" />
<div class="code">
<pre class="prettyprint">
NSString *name =
((UITextField *)[((UITableViewCell*)[self.view viewWithTag:i]).contentView viewWithTag:2]).text;
</pre>
</div>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitSGGNRi9sFY8f-rKeP1dh2aV7FxIlu7oeyRH9jBoqBauXHHPKTekPTp3E30Ppxbspv93FBMGBpzi8zwfsMDwMU7MTsuzpnUsHlRMQH_StpilvmydijW4AZ2oUjBFVFaDd9YjqaaSAR9Ib/s400/joker3.png" alt="" />
<div class="code">
<pre class="prettyprint">
[[[scrollView viewWithTag:100 + currentPage + 2] viewWithTag:22] removeFromSuperview];
</pre>
</div>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWaThGKwZlMj9FIvsAedbKJCMY26t6QHHaAUSbddYzM6kNZmbZEzcgVQ3_9GZcx7R1h1iZ8PWGlHVa6RCn2uCEMM0Qe8ksOW66-wYQUBcLzrQjpxCCW46O-NqPl6igNWcwIw82fomtGojx/s400/joker4.png" alt="" />
<div class="code">
<pre class="prettyprint">
homeButton.tag = (int)@"home";
</pre>
</div>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNRF9uZtLzS0Ealc-kK8AivfL-UUmpi6FoLCq-agxwzMMJ7wySBm-rTfucN4Igl6L-C1-qvi_nO4NdWUFpEvlZS3crK_FOWbZVcXbBqvXgwY3hzobPJXfXkpqC4CRdt0R1Fgm9NTSawm6l/s400/joker5.jpg" alt="" />
<p>Yes folks, these all come from real production code. Did I mention I love my job?</p>
<h2>The correct way to associate extra information with a view</h2>
<p>When a developer writes code like this:</p>
<div class="code">
<pre class="prettyprint">
NSUInteger photoIndex = thumbnailButton.tag - 1;
</pre>
</div>
<p>What he really wants to write is this:</p>
<div class="code">
<pre class="prettyprint">
NSUInteger photoIndex = thumbnailButton.photoIndex;
</pre>
</div>
<p>Or even:</p>
<div class="code">
<pre class="prettyprint">
Photo *selectedPhoto = thumbnailButton.photo;
</pre>
</div>
<p>The way to achieve this is obvious. You can create a custom subclass with additional properties to store the extra information you need.</p>
<p>In this case we have a button which is associated with a given photo, so we create a <code>UIButton</code> subclass and add a property to store the associated photo index, or, even better, a reference to the Photo object itself:</p>
<div class="code">
<pre class="prettyprint">
@interface PhotoThumbnailButton : UIButton
@property (nonatomic, assign) NSInteger photoIndex;
// OR
@property (nonatomic, strong) Photo *photo;
@end
</pre>
</div>
<p>Now when we want to get or set the associated photo for a button, we just use these public properties. Our code will be much clearer than if we had used tags and array indexes and weird additions and subtractions.</p>
<p>In some cases, creating a subclass is not possible, or it may seem a little overkill given your circumstances. In these cases, you can achieve similar improvements to your code by making use of Objective-C associated references.</p>
<h3>Associated references</h3>
<p><a href="https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocAssociativeReferences.html">Associated references</a> make use of <a href="https://developer.apple.com/library/ios/documentation/cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/func/objc_setAssociatedObject"><code>objc_setAssociatedObject</code></a> and <a href="https://developer.apple.com/library/ios/documentation/cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/func/objc_getAssociatedObject"><code>objc_getAssociatedObject</code></a> to attach values to an existing object at runtime.</p>
<p>In our case we can write a couple of helper methods like this:</p>
<div class="code">
<pre class="prettyprint">
#import <objc/runtime.h>
static char kThumbnailButtonAssociatedPhotoKey;
// ...
- (void)setAssociatedPhoto:(Photo *)associatedPhoto
forThumbnailButton:(UIButton *)thumbnailButton
{
objc_setAssociatedObject(thumbnailButton,
&kThumbnailButtonAssociatedPhotoKey,
associatedPhoto,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (Photo *)associatedPhotoForThumbnailButton:(UIButton *)thumbnailButton
{
return objc_getAssociatedObject(thumbnailButton,
&kThumbnailButtonAssociatedPhotoKey);
}
</pre>
</div>
<p>Now we can easily set/get the associated photo for a button:</p>
<div class="code">
<pre class="prettyprint">
- (void)configureThumbnailButtonForPhoto:(Photo *)photo
{
// ...
[self setAssociatedPhoto:photo
forThumbnailButton:thumbnailButton];
// ...
}
- (void)thumbnailButtonTapped
{
Photo *photo = [self associatedPhotoForThumbnailButton:thumbnailButton];
// ...
}
</pre>
</div>
<p>So with a couple of short helper methods, we can easily attach model objects to our UI controls. Associated references are very cool.</p>
<h2>The only (semi-)acceptable way to use tags</h2>
<p>Let’s assume you aren’t trying to store data in a view’s tag. Instead, you just want a quick and dirty way to grab a reference to a view. Is it OK to use tags in these situations?</p>
<p>Well, in almost every case I can think of, it is better to store a reference to the view using a real property somewhere, whether that’s an <code>IBOutlet</code> or just a regular property on your class.</p>
<p>Do you need to add some custom views to a <code>UITableViewCell</code>? Subclass it and add real properties. Need to know which of many <code>UIAlertView</code>s is calling your <code>alertView:clickedButtonAtIndex:</code> method? Assign the alerts to properties when you create them, and compare the pointers directly.</p>
<p>By using real properties you get stronger typing, better naming, better visibility of the moving parts of your app, and you don’t have to down-cast <code>viewWithTag</code>’s <code>UIView*</code> return type. You also get better performance because <code>viewWithTag:</code> must traverse the view hierarchy for every call.</p>
<p>To me, using tags seems to be another pattern driven purely by laziness. Adding a property to your parent object is not difficult, especially now that we’ve all upgraded to ARC and Xcode 4.4, where <code>-dealloc</code> and <code>@synthesize</code> are unnecessary in most cases. You have upgraded, haven’t you?</p>
<h3>But mooooom…</h3>
<p>Oh alright then. If you <em>do</em> decide to use tags, you must follow our ground rule and only store unique identifiers for your views. Furthermore, we can say:</p>
<blockquote>
<p><code>UIView</code>’s <code>tag</code> property should <em>only</em> be given a named <code class="prettyprint">#define</code> or <code class="prettyprint">enum</code> value.</p>
</blockquote>
<p>For example, this is good:</p>
<div class="code">
<pre class="prettyprint">
enum MyViewTags {
kTitleLabelTag = 1,
kSendButtonTag,
kSomeOtherViewTag
};
// ...
if (sender.tag == kSendButtonTag) {
// ...
}
</pre>
</div>
<p>The last thing we want are magic numbers flying around in our code. Always create named constants for your tag values, otherwise you end up with this kind of stuff:</p>
<div class="code">
<pre class="prettyprint">
aiView.tag = 22;
</pre>
</div>
<div class="code">
<pre class="prettyprint">
content.tag = 111;
</pre>
</div>
<div class="code">
<pre class="prettyprint">
globalSyncAlert.tag = 1000;
</pre>
</div>
<div class="code">
<pre class="prettyprint">
nextZoomingView.tag = 2000;
</pre>
</div>
<div class="code">
<pre class="prettyprint">
infoView.tag = 3000
</pre>
</div>
<div class="code">
<pre class="prettyprint">
white.tag = 1111;
</pre>
</div>
<div class="code">
<pre class="prettyprint">
howto.tag = 4357824;
</pre>
</div>
<div class="code">
<pre class="prettyprint">
imageView.tag = 199;
</pre>
</div>
<div class="code">
<pre class="prettyprint">
self.tag = 999;
</pre>
</div>
<div class="code">
<pre class="prettyprint">
label.tag = 3542
</pre>
</div>
<div class="code">
<pre class="prettyprint">
homeVC.view.tag = 1234;
</pre>
</div>
<div class="code">
<pre class="prettyprint">
b.tag = 1983;
</pre>
</div>
<p>Again, these are all real-world examples. I like to collect them.</p>
<h2>Summary</h2>
<p>In summary, try to avoid using <code>UIView</code> tags as much as possible. Follow these rules:</p>
<ul>
<li>Don’t store data in a view’s tag. Prefer subclassing and Objective-C associated references to associate additional information with a view.</li>
<li>Prefer real properties and XIB outlets over tags for getting references to subviews.</li>
<li>If you do use tags, do not use magic numbers. Use named constants.</li>
</ul>
<p>Follow these rules and your code will be much better off. Your fellow developers will thank you.</p>Unknownnoreply@blogger.com14tag:blogger.com,1999:blog-5863548874298958343.post-59463954671111877022012-07-23T07:00:00.000+02:002012-08-10T22:13:48.442+02:00You're Doing It Wrong #3: error:NULL<p>
This week's post is going to be short and simple, and it relates to
error handling.
</p>
<p>
In Objective-C, a common way to report error information to the
caller of a method is to use an <code>NSError</code> output
argument. For example, here is the declaration of
the <code>writeToFile:options:error</code> method
on <code>NSData</code>:
</p>
<div class="code">
<pre class="prettyprint">
- (BOOL)writeToFile:(NSString *)path
options:(NSDataWritingOptions)mask
error:(__autoreleasing NSError **)errorPtr;
</pre>
</div>
<p>
The method returns a boolean to indicate success or failure. On
failure, a pointer to an <code>NSError</code> object will be written
to the <code>error</code> output argument (note the double
stars). All very standard.
</p>
<p>
What I see too often is code that simply passes
<code>NULL</code> to the <code>error</code> argument and doesn't
bother to check the return value. This ignores or hides any errors
that may be generated by the method:
</p>
<div class="code">
<pre class="prettyprint">
NSData *data = [self makeData];
[data writeToFile:outputFile
options:NSDataWritingAtomic
error:<span class="highlight">NULL</span>];
</pre>
</div>
<p>
In my opinion this is just as bad as gobbling up exceptions in Java:
</p>
<div class="code">
<pre class="prettyprint">
try {
doSomething();
} catch (Throwable e) {
}
</pre>
</div>
<p>
Swallowing errors like this is very much frowned upon. It can lead
to nightmares in terms of maintainability and debugging, especially
in a language like Objective-C where <code>nil</code> return values
can go unnoticed and delay the symptoms of an error.
</p>
<h2>Laziness</h2>
<p>
I think the reason so many developers fall into this habit is due to
laziness. In order to do things properly, you have to declare a new
variable, wrap the method you are calling in an if statement, and
somehow deal with the error. You may decide you have to pass the
error up a level, which would require you to add error feedback to
your own interface.
</p>
<p>
These annoying details crop up when you are already half-way through
writing the method call, so it's almost understandable that people
get frustrated and stuff in a <code>NULL</code> to get it over and
done with.
</p>
<p>
It's still <em>wrong</em>, however. And you know it's wrong. So
please, for the sake of professionalism and your fellow developers,
get into the habit of <em>always</em> providing a value to
the <code>error</code> argument. At the very least you should be
logging the error:
</p>
<div class="code">
<pre class="prettyprint">
NSData *data = [self makeData];
NSError *error;
if (![data writeToFile:outputFile
options:NSDataWritingAtomic
error:&error]) {
MyLogError(@"%@", error);
}
</pre>
</div>
<p>
I don't even care whether or not you describe what you were doing in
the message. Just stuff a <code>@"%@"</code> in there and get it
done as quickly as possible. At least the error will
be <em>seen</em>. This is the absolute minimum, and you should do
this for <em>every</em> method call that provides error information.
</p>
<p>
Even if you are writing quick prototype or test code, I would also
suggest you follow this rule. Indeed, these are the situations where
you are most likely to make mistakes, and breaking into the debugger
to see which method failed is a huge waste of time. It is much
faster to write the code properly and get quick feedback on any
problems.
</p>
<h2>Rules are there to be broken</h2>
<p>
Yes yes, OK. Rules are there to be broken, so what follows is one
example where it may (<em>may</em>) be acceptable to ignore an
error:
</p>
<div class="code">
<pre class="prettyprint">
- (void)copySourceFileToDestination {
NSString *source = [self sourcePath];
NSString *destination [self destPath];
NSFileManager *manager = [NSFileManager defaultManager];
// Delete/overwrite destination
// ignore error because destination might not exist
[manager removeItemAtPath:destination
error:NULL];
NSError *error;
if (![manager copyItemAtPath:source
toPath:destination
error:&error]) {
MyLogError(@"Error copying file: %@", error);
// ...
}
// ...
}
</pre>
</div>
<p>
In this example we want to copy path <code>source</code>
to <code>destination</code>, overwriting <code>destination</code> if
necessary.
</p>
<p>
The <code>copyItemAtPath:toPath:error:</code> method will fail
if <code>destination</code> already exists. To get proper
overwriting behaviour we either have to
implement <code>NSFileManagerDelegate</code>, or instead (as in this
example) delete <code>destination</code> first with a call
to <code>removeItemAtPath:error</code>.
</p>
<p>
In all likelihood, <code>destination</code> will not exist, so the
call to <code>removeItemAtPath:error</code> is going to fail. We
don't care about this particular failure case, so we ignore it. If
anything else <em>does</em> go wrong, we still check the result of
<code>copyItemAtPath:toPath:error:</code>, so we seem to be in the
clear.
</p>
<h2>Implementing methods that return errors</h2>
<p>
I'm going to close this off by giving a little tip for when you
write your own methods that return error information.
</p>
<p>
If somebody calls <em>your</em> code with a <code>NULL</code> error
value, you want to be as helpful as possible and log the error for
them:
</p>
<div class="code">
<pre class="prettyprint">
- (BOOL)myAPIMethod:(__autoreleasing NSError **)errorOut
{
// do some work
// ...
if (weGotErrors) {
if (errorOut) {
*errorOut = theErrorWeGot;
} else {
MyLogError(@"Error doing something: %@",
theErrorWeGot);
}
}
// ...
}
</pre>
</div>
<p>
If we are provided with a non-NULL output argument, we write out the
error and it is up to the caller to log, handle or ignore the error
as they wish.
</p>
<p>
If we are given <code>NULL</code>, we're going to assume the
developer is lazy and log the error for them. If
they <em>really</em> want to ignore the error, they can provide an
output argument and do the ignoring in their own
code. In <em>our</em> code we are going to be responsible developers
and make sure errors are <em>visible by default</em>.
</p>
<h2>Be responsible</h2>
<p>
Things can get tedious in Objective-C. Error handing can be annoying
and can make an already ugly block of code even uglier. But stay
true to your core values, be responsible, and put in that extra bit
of effort to write robust and programmer-friendly code.
</p>
<p>
That's the end. Thanks for reading.
</p>Unknownnoreply@blogger.com10tag:blogger.com,1999:blog-5863548874298958343.post-86808357099146994772012-07-19T23:49:00.000+02:002012-07-25T08:15:02.664+02:00You're Doing It Wrong #2: Sizing labels with -[NSString sizeWithFont:...]<p class="authors_note">
Author's note: Well, I've already blown my one-post-per-week
target. <code>UIButton</code>'s insets behaviour finally got the
best of me and I had to take a major detour to settle the issue once
and for all. I hope it was worth it!
</p>
<p>
<hr />
</p>
<p>
It's very common to want to adjust the bounds of
a <code>UILabel</code> to fit its contents. The
most common technique I've seen from developers looks something like
this:
</p>
<div class="code">
<pre class="prettyprint">
UILabel *label = [[UILabel alloc] initWithFrame:...];
label.text = NSLocalizedString(@"Some long text here...");
label.numberOfLines = 0;
CGSize maxSize = CGSizeMake(label.bounds.size.width, CGFLOAT_MAX);
CGSize textSize = [label.text sizeWithFont:label.font
constrainedToSize:maxSize];
label.frame = CGRectMake(10, 10, textSize.width, textSize.height);
</pre>
</div>
<p>
This code is using one
of <code>NSString</code>'s <code>sizeWithFont:...</code> methods to
calculate the bounds of the label's text, taking its font and width
into consideration.
</p>
<p>
If you are sizing your labels like this, you need to read on
because you are <em>doing it wrong</em>.
</p>
<h2>A smell</h2>
<p>
Let's take a step back and think about this for a moment.
<p>
<p>
We want to know how much space the label needs to display its
text. Surely that logic belongs in <code>UILabel</code>? Only the
label itself really knows how it renders its content and what
offsets or margins it may be applying.
</p>
<p>
It seems like a bit of a smell to me that we have to calculate this
stuff ourselves using methods on another class.
</p>
<p>
Now in the case of <code>UILabel</code>, it
turns out that <code>-sizeWithFont:</code>
returns exactly the size we need. The label is probably doing a
simple <code class="prettyprint">-[NSString drawAtPoint:...]</code>
which matches up perfectly with the results we get back from
the <code>sizeWithFont:...</code> methods. But
is this always going to be true?
</p>
<p>
What if <code>UILabel</code> decides to add support for special
borders, or configurable line heights, or some other visual effects
that will change the required bounds? The above code is going to
break. It isn't future proof, and we are essentially duplicating or
even worse
<em>guessing</em> the behaviour of <code>UILabel</code>'s rendering.
</p>
<p style="float: right;">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizh7Zw9RmhQwX6iFsC4LGuaZOgaCE-BmWN8OXw9cQk94o4GRwalz_jlZMDcz4lxz-i5WAmpkDUnvS_Sh0a0wwu6yRYlomk_4BfKXBuq2-DuVjzdXsiiECzSzSXMwKZKCNzTXLxQlH29GUD/s400/attributed_string_uilabel.png" alt="An example of using an attributed string with a UILabel in iOS 6" />
</p>
<p>
Is <code>UILabel</code> really going to change in such a manner?
Well, it just did. As of iOS 6, <code>UILabel</code> supports the
rendering of attributed strings. This means arbitrary ranges in the
label's text can have different fonts and styles applied to them. If
there is word in the middle of the label with a very large font,
bounds required to fit that string in the label are going to
increase.
</p>
<p>
If you use the previous code unmodified on a label containing an
attributed string, you are going to get incorrect results.</p>
<p>
As it turns out, that there are UIKit additions
to <code>NSAttributedString</code>,
namely <code>boundingRectWithSize:options:context:</code>, which
provide similar functionality
to <code>NSString</code>'s <code>-sizeWithFont:</code> methods. But
our code still should not be duplicating this kind of logic,
especially when there is a far better and simpler solution...
</p>
<h2><code>sizeToFit</code>
and <code>sizeThatFits:</code></h2>
<p>
If we want to resize a label to fit its contents, we can just tell
it to do so:
</p>
<div class="code">
<pre class="prettyprint">
[label sizeToFit];
</pre>
</div>
<p>
Bam. Done. The label will take its current width, and adjust its
height to fit its contents (assuming it is a multi-line label). If
the label has a width of 0, its size is adjusted to fit everything
on a single line.
</p>
<p>
If you wish to size the label without setting a frame beforehand,
you can ask the label for the size it needs like this:
</p>
<div class="code">
<pre class="prettyprint">
CGSize maxSize = CGSizeMake(200.0f, CGFLOAT_MAX);
CGSize requiredSize = [label <span class="highlight">sizeThatFits</span>:maxSize];
label.frame = CGRectMake(10, 10, size.width, size.height);
</pre>
</div>
<p>
Note the use of <code>CGFLOAT_MAX</code> here to
mean "unbounded".
</p>
<p>
Both <code>sizeToFit</code> and <code>sizeThatFits:</code> are
standard in UIKit and have existed for a very long time. They work
with the new attributed string support in iOS 6, and will continue
to work no matter what changes are made to <code>UILabel</code>.
</p>
<p>
It pains me to see people writing useless (and often times
incorrect) <a href="https://gist.github.com/1005520">categories
on <code>UILabel</code></a> for something as standard as this. I
guess the lesson to take away is to explore as much of the
documentation as you can. I'm sure there are many useful methods out
there that I've overlooked.
</p>
<h2>Going a little deeper</h2>
<p>
The documentation
for <a href="http://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/occ/instm/UIView/sizeToFit"><code>sizeToFit</code></a>
and <a href="http://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/occ/instm/UIView/sizeThatFits:"><code>sizeThatFits:</code></a>
can be found in
the <a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html">UIView</a>
class reference.
</p>
<p>
What you need to know is that <code>sizeThatFits:</code> is
overridable and returns the "most appropriate" size for the control
that fits the constraints passed to it. The method <em>can</em>
decide to ignore the constraints if they cannot be met.
</p>
<p>
<code>sizeToFit</code> will simply call through
to <code>sizeThatFits:</code> passing the view's current size as the
argument. It will then update the view's frame based on the value it
gets back. So all the important logic goes
in <code>sizeThatFits:</code>, and this is the method you should
override for your own custom controls.
</p>
<h2>A major detour: <code>UIButton</code> insets demystified</h2>
<p>
Many of the standard UIKit controls
implement <code>sizeThatFits:</code>, one of which
is <code>UIButton</code>. However, things can get a little tricky
with <code>UIButton</code>, especially when when you throw insets
into the mix.
</p>
<p>
We'll start by creating a button with an image, a stretchable
background image, and some text:
</p>
<div class="code">
<pre class="prettyprint">
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
[b setBackgroundImage:[self buttonBackgroundImage]
forState:UIControlStateNormal];
[b setImage:[self buttonImage]
forState:UIControlStateNormal];
[b setTitle:NSLocalizedString(@"Click me!", nil)
forState:UIControlStateNormal];
[b sizeToFit];
</pre>
</div>
<p>
We call <code>sizeToFit</code> and end up with
this:
</p>
<p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgx1sbQcENWPxwmmNsyZH83aoGl4pMKABio7i81SG4PC_UGjBdiR-31ZE4XMerlxykhukJG8CIAcCaLFWE7W5H2wJMm8_FiaIli6qNuRW3ZPmoDHQ2voSJKX_5JrVp3ej7Kfh9OjuRBnGs7/s400/uibutton_1.png" alt="" />
</p>
<p>
The button elements are all crammed together with no spacing. This
is expected, and to fix this we need to give the button some insets.
</p>
<p>
<code>UIButton</code> provides
three <code>UIEdgeInsets</code> properties that
you can play with to adjust the spacing of the elements in the
button. These
are <code>contentEdgeInsets</code>, <code>imageEdgeInsets</code>
and <code>titleEdgeInsets</code>.
</p>
<p>
If you've ever tried adjusting these in Interface Builder, you'll
know things can get a little... interesting. For example, you may
have tried increasing <code>imageEdgeInsets.left</code> 1 point at a
time and seen how the button image seems to move unpredictably,
sometimes making big steps between values:
</p>
<p>
<img src="http://www.mikeweller.com/images/image_left_insets.gif" />
</p>
<p>
The reason for this is that a positive inset value will shrink the
layout rectangle for the image and give you you unpredictable
results as the button tries to fit the image into a bounding box
which is too small.
</p>
<p>
The <a href="http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIKitDataTypesReference/Reference/reference.html#//apple_ref/c/tdef/UIEdgeInsets">documentation
for <code>UIEdgeInsets</code></a> describes what insets represent:
</p>
<blockquote>
Edge inset values are applied to a rectangle to shrink or expand the
area represented by that rectangle. Typically, edge insets are used
during view layout to modify the view’s frame. Positive values cause
the frame to be inset (or shrunk) by the specified amount. Negative
values cause the frame to be outset (or expanded) by the specified
amount.
</blockquote>
<p>
What this means is that if we want to reliably shift the image or
text, we must add or subtract equal (but opposite) amounts to both
left/right or top/bottom insets.
</p>
<p>
Confused? I'm not surprised. To help you visualize all this more
easily and see the effect of <code>sizeToFit</code> at the same
time, I've written a little iPhone app called
ButtonInsetsPlayground. <a href="https://github.com/MikeWeller/ButtonInsetsPlayground">The
source is available on github</a>.
</p>
<p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6EiFGaJWQfA64zp-cOy7XBQoA2xhWev1vDoekkZ5BJbwRDnCDP3il9tl3wmfwKEYlsmpWCoSgmThcJAfd1IHFju8x-SmtcDCxMDrlnokducYr4V9EqxQO27-wWfxCviIAWkJhCeNepAZZ/s400/ButtonInsetsPlayground.png" />
</p>
<p>
Please forgive the
<em>made-by-a-programmer</em> UI, this is purely for testing.
</p>
<p>
If you play around with this UI for a while, you should end up even
more confused than you were before. I seriously considered cracking
out IDA and diving in to the <code>UIButton</code> internals to
figure out what is going on, but I really want to finish this post.
(hint to the curious: the relevant selectors are <code>-[UIButton
contentRectForBounds:]</code>, <code>-[UIButton
titleRectForContentRect:]</code> and <code>-[UIButton
imageRectForContentRect:]</code>)
</p>
<p>
What you need to know is the following...
</p>
<h3><code>contentEdgeInsets</code></h3>
<p>
<code>contentEdgeInsets</code> is pretty intuitive and will behave
as you expect. You can easily add space around both the image and
text to pad things out nicely. Use positive values to inset the
content. The implementation of <code>sizeThatFits:</code> causes the
button to grow appropriately when we call <code>sizeToFit</code>:
</p>
<p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNLpfa1OcXc_lOBEmJfDh2k4bApi0VVbHqOf9-nsSHZQ1zS9D0HfMWt20UgeoXtUzHicJa8fn-VxnLgM38AA97xgu4QsNz2pBBHAzzxn8hZ7TVotWuzGeyf6mlg8S4Dk4PdopquCjX_Akf/s400/content_insets_zero.png" />
<br />
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibxilkNDfJ98TNXu4-ORaiBcTZJVJVQXcGsU5enrjvTU4fi3b88IB9cfwB51oc9Mz4cr6s7XVyXZz8qLVea4zwRWrFNeiPju-h9GfGAMmk3Q38F6dWh6untPm2reNV4La7Aat8IA0IDpA0/s400/content_insets_left_right.png" />
</p>
<p>
<strong>UPDATE:</strong> I originally wrote about how it's possible
to get pixel misaligned images with certain content
insets. Naturally, this turned out to be my own fault.
</p>
<h3><code>imageEdgeInsets</code> and <code>titleEdgeInsets</code></h3>
<p>
The golden rule when it comes to these two insets is to add equal
and opposite offsets to the left and right insets. So if you add 5pt
to the left title inset, you must apply -5pt to the right. This
means you are using these insets only to <em>offset</em> the image
or text, not to resize them in any way.
</p>
<p>
If you do not follow this rule, the calculated layout rect for the
title (or image) may become too small and you risk text truncation
and other unexpected results:
</p>
<p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOEqeZQzoY7CfNfYNgWjTNkTE79Xp6HGPYNK2VYYSyRoI1Pb2t4YQNtL6e0pTz6wroK1BRQe9vZMW9ZHB8GQ0e92yS9EFb_TG6AdPUI3Q-7fI3ZWZDi1Gz2dVUhCiy9SPqUYKoIuHyEHkD/s400/title_truncation.png" />
</p>
<p>
This problem may not reveal itself until you have a string of the
appropriate length, so if the text in your buttons is dynamic or
localization-aware you need to be careful.
</p>
<p>
The top/bottom insets do not seem to have any major issues, but you
should probably follow the same rule for these as well.
</p>
<p>
<code>UIButton</code>'s mystical insets behaviour could be the topic
of an entire blog post of its own, but I think we have enough
information to continue on our way.
</p>
<h3>Finishing up</h3>
<p>
Back to our button.
</p>
<p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgx1sbQcENWPxwmmNsyZH83aoGl4pMKABio7i81SG4PC_UGjBdiR-31ZE4XMerlxykhukJG8CIAcCaLFWE7W5H2wJMm8_FiaIli6qNuRW3ZPmoDHQ2voSJKX_5JrVp3ej7Kfh9OjuRBnGs7/s400/uibutton_1.png" alt="" />
</p>
<p>
We want to space out the elements a little better, and make
sure <code>sizeToFit</code> does the right thing.
</p>
<p>
First we'll add some left and right content insets:
</p>
<div class="code">
<pre class="prettyprint">
// ...
UIEdgeInsets contentInsets =
UIEdgeInsetsMake(0.0f, 15.0f, 0.0f, 15.0f);
[b setContentEdgeInsets:contentInsets];
[b sizeToFit];
</pre>
</div>
<p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5szgmg3P0glBBYHSzQ_K3QruuMtUqQcBJgtixER5bpV3XJxvL_RuNUhsXFhRcOPPMJhxk24aMc8nlyuzJ0Vf4w0ou6STmASNS_pLdI3AjdxQyYy6T9WaYnve3RCHDLGApSg48Lfjsq8wv/s400/uibutton_2.png" alt="" />
</p>
<p>
Next we want to shift the text to the right, to create some space
between it and the image. Following our golden rule, we add equal
but opposite amounts to the left and right insets:
</p>
<div class="code">
<pre class="prettyprint">
// ...
UIEdgeInsets titleInsets =
UIEdgeInsetsMake(0.0f, <span class="highlight">8.0f</span>, 0.0f, <span class="highlight">-8.0f</span>);
UIEdgeInsets contentInsets =
UIEdgeInsetsMake(0.0f, 15.0f, 0.0f, 15.0f);
[b setTitleEdgeInsets:titleInsets];
[b setContentEdgeInsets:contentInsets];
[b sizeToFit];
</pre>
</div>
<p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjl5AJ3woY3oQec1-tPty0nh3X2VnwSzVyTL7M-udKp5KjxB3MR-Ymsrel1ZNRPaVtMDPsWYfpN8XY2tFRccL3k-oJrPj03GL7xg0wk52Zl1R-meDLLvsDM1SW-sOq9x91AH6EQDGq4c6rA/s400/uibutton_3.png" alt="" />
</p>
<p>
Finally, we adjust the <em>content</em> insets again to add some
extra space on the right for our inset text:
</p>
<div class="code">
<pre class="prettyprint">
UIEdgeInsets titleInsets =
UIEdgeInsetsMake(0.0f, 8.0f, 0.0f, -8.0f);
UIEdgeInsets contentInsets =
UIEdgeInsetsMake(0.0f, 15.0f, 0.0f, 15.0f);
CGFloat extraWidthRequiredForTitle =
titleInsets.left - titleInsets.right;
<span class="highlight">contentInsets.right += extraWidthRequiredForTitle</span>;
[b setTitleEdgeInsets:titleInsets];
[b setContentEdgeInsets:contentInsets];
[b sizeToFit];
</pre>
</div>
<p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiFiRVcPjhg8mX7WBIDQ-iw3__-ahfZ-SSG917_jd1KLYKNsqPIsO00u9HlfgiHR5DrQOF17uy9fQ5sf3PW6eb4lv6AkyIFjFs3UkgOFIDeJkLynepz33QFY4L6667R_PdAcxsow5unE8Hw/s400/uibutton_4.png" alt="" />
</p>
<p>
And at long last, we're finished. We can set arbitrarily long titles
on the button, call <code>sizeToFit</code>, and we get correct
results.
</p>
<p>
I hope this has been useful. If you can provide further insight
into <code>UIButton</code>'s layout behaviour, I'd love to hear from
you!
</p>Unknownnoreply@blogger.com22tag:blogger.com,1999:blog-5863548874298958343.post-74763084117972305492012-07-09T22:53:00.000+02:002012-07-09T22:53:11.555+02:00You're Doing It Wrong #1: NSLog("Debug"); (iOS Development)<p>
Logging. Ah, yes... the age-old problem.
</p>
<p>
In the world of iOS development, the
trusty <code class="prettyprint">NSLog</code> macro is used by many
to print out debug information.
</p>
<p>
It's not uncommon to see delights such as this in a battle-worn
developer's code:
</p>
<div class="code">
<pre class="prettyprint">
NSLog(@"DEBUG: got here 2");
while ([self retainCount]) {
[self release];
NSLog(@"DEBUG: retain count is now: %u", [self retainCount]);
// lol i have no idea what i am doing
}
</pre>
</div>
<p>
If we look past the egregious memory management techniques being
employed here, we see some pretty
typical <code class="prettyprint">NSLog</code> usage. The problem
here is that <code class="prettyprint">NSLog</code> is not actually
meant for debug messages such as these.
</p>
<p>
If we
read <a href="https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/miscellaneous/foundation_functions/reference/reference.html#//apple_ref/c/func/NSLog">the
<code class="prettyprint">NSLog</code> documentation</a> we find this description:
</p>
<blockquote>
<dl>
<dt><code class="prettyprint">NSLog</code></dt>
<dd>Logs an error message to the Apple System Log facility.</dd>
</dl>
</blockquote>
<p>
Logs an <em>error</em> to the Apple System Log facility. Not a debug
message, an <em>error</em>.
</p>
<p>
So what does this matter as long as we see the message in the debug
console?
</p>
<p>
Well, the problem is that <code class="prettyprint">NSLog</code>
messages will appear in a device's log <em>even in release
builds</em>.
</p>
<p>
To demonstrate this, I tapped around some of the apps
on my iPhone. Looking at the device console via Xcode's Organizer, I
saw a bunch of messages which are clearly meant for debugging
purposes:
</p>
<p><strong>Flight Control</strong></p>
<pre>
FlightControl[12724] <Warning>: Free space on file system: 2537136128 bytes
FlightControl[12724] <Warning>: authenticateWithCompletionHandler: enter
FlightControl[12724] <Warning>: authenticateWithCompletionHandler: exit
FlightControl[12724] <Warning>: ---URLSTR: file:///var/mobile/Applications/.../Library/Caches/CC_Data/index.htm
FlightControl[12724] <Warning>: query: (null)
FlightControl[12724] <Warning>: ---URLSTR: file:///var/mobile/Applications/.../FlightControl.app/res/more_games/index.htm
FlightControl[12724] <Warning>: query: (null)
FlightControl[12724] <Warning>: Web cache local version (v-1) is out of date, getting new version (v11)
FlightControl[12724] <Warning>: Wrote 856 bytes to '/var/mobile/Applications/.../Library/Caches/CC_Data/index.htm'
FlightControl[12724] <Warning>: Wrote 736 bytes to '/var/mobile/Applications/.../Library/Caches/CC_Data/0.jpg'
FlightControl[12724] <Warning>: Wrote 66787 bytes to '/var/mobile/Applications/.../Library/Caches/CC_Data/1.jpg'
FlightControl[12724] <Warning>: Wrote 105286 bytes to '/var/mobile/Applications/.../Library/Caches/CC_Data/2.jpg'
FlightControl[12724] <Warning>: Wrote 736 bytes to '/var/mobile/Applications/.../Library/Caches/CC_Data/3.jpg'
FlightControl[12724] <Warning>: Wrote 736 bytes to '/var/mobile/Applications/.../Library/Caches/CC_Data/4.jpg'
FlightControl[12724] <Warning>: Wrote 736 bytes to '/var/mobile/Applications/.../Library/Caches/CC_Data/5.jpg'
</pre>
<p>
<strong>PONS English <-> Deutsch Dictionary</strong>
</p>
<pre>
...
Phrasebook[15109] <Warning>: Morphologies: (
{
Basename = 4001;
Filename = "4001.sdc";
LanguageFrom = 1818717797;
Path = "Phrasebook.app/4001.sdc";
Type = 3;
},
{
Basename = 4004;
Filename = "4004.sdc";
LanguageFrom = 1836213607;
Path = "Phrasebook.app/4004.sdc";
Type = 3;
}
)
Phrasebook[15109] <Warning>: Image test_background can't be loaded!
Phrasebook[15109] <Warning>: Image test_background can't be loaded!
</pre>
<p><strong>Angry Birds</strong></p>
<pre>
AngryBirds[15177] <Warning>: --> activateCrystalSetting: [set 2][val YES]
AngryBirds[15177] <Warning>: --> activateCrystalSetting: [set 2][val NO]
AngryBirds[15177] <Warning>: --> activateCrystalSetting: [set 2][val YES]
AngryBirds[15177] <Warning>: --> activateCrystalSetting: [set 2][val NO]
</pre>
<p><strong>Red laser</strong></p>
<pre>
RedLaser[15191] <Warning>: textLabel width: 0.000000
RedLaser[15191] <Warning>: textLabel height: 0.000000
</pre>
<p><strong>Justin.tv</strong></p>
<pre>
Justin.tv[15256] <Warning>: [Log Level: 4]; My Base URL is (null)
Justin.tv[15256] <Warning>: [Log Level: 4]; Final URL = https://ws.tapjoyads.com/get_vg_store_items/user_account?country_code=GB&display_multiplier=1.000000&library_version=8.1.7&udid=6e5e93e74df482fbf7f583d8c734d2ef32a1038c&app_id=48d87890-12f9-4a3e-9091-ec7d6d67beb1&lad=0&mobile_country_code=262&device_type=iPhone&connection_type=wifi&carrier_name=Telekom.de&language_code=en&os_version=5.1.1&publisher_user_id=6e5e93e74df482fbf7f583d8c734d2ef32a1038c&verifier=981aeeb7e59cd9f79ecb20390578c13906ca821c777f93541fb2e4959a8b91dc×tamp=1339496108&allows_voip=yes&app_version=3.7.4&mobile_network_code=01&carrier_country_code=de&platform=iOS&mac_address=145a059a0c78&device_name=iPhone3%2C1
Justin.tv[15256] <Warning>: [Log Level: 4]; Update Account Info Response Returned
Justin.tv[15256] <Warning>: [Log Level: 4]; TJC: Updating Currency Name in Cache
</pre>
<p><strong>Dropbox</strong></p>
<pre>
Dropbox[12755] <Warning>: [ANALYTICS] {"retry":0,"favorite":false,"extension":"txt","id":[snip],"cached":false,"ts":"1341324832.83","event":"file.view.start","size":133}
Dropbox[12755] <Warning>: [INFO] DocumentViewController -(void)startLoading
Dropbox[12755] <Warning>: [ANALYTICS] {"id":[snip],"ts":"1341324832.88","size":133,"event":"download.start","extension":"txt","connection":"wifi"}
Dropbox[12755] <Warning>: [INFO] FileViewController - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation orientation = 1
Dropbox[12755] <Warning>: [ANALYTICS] {"path_hash":[snip],"event":"metadata.load.success","ts":"1341324833.14"}
Dropbox[12755] <Warning>: [ANALYTICS] {"ts":"1341324833.56","screen":"DocumentViewController","event":"screen.view"}
Dropbox[12755] <Warning>: [INFO] FileViewController - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation orientation = 4
Dropbox[12755] <Warning>: [INFO] DocumentViewController - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
Dropbox[12755] <Warning>: [INFO] FileViewController - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
Dropbox[12755] <Warning>: [ANALYTICS] {"id":[snip],"ts":"1341324834.89","size":133,"event":"download.success","extension":"txt"}
Dropbox[12755] <Warning>: [INFO] DocumentViewController - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 5 url = about:blank
Dropbox[12755] <Warning>: [INFO] DocumentViewController 0x4bb4640 - (void)webViewDidStartLoad:(UIWebView *)webView 0x4bbf870
Dropbox[12755] <Warning>: [ANALYTICS] {"id":[snip],"event":"file.view.success","ts":"1341324835.41"}
Dropbox[12755] <Warning>: [INFO] DocumentViewController 0x4bb4640 - (void)webViewDidFinishLoad:(UIWebView *)webView 0x4bbf870
</pre>
<p>
This is messy. And this blog post post was looking pretty slick
before I pasted this crap in.
</p>
<p>
Debug messages like this should never appear in a
release build, at least by default. They clutter up the device log
with unimportant developer left-overs, and can potentially reveal
sensitive information about an app or user.
</p>
<p>Now sure, the logs shouldn't really be accessible to outside
parties, but it's still a bad idea to allow this kind of information
to leak from your app. Quite simply, it's unprofessional.
</p>
<p>As you can see from the logs above (and by testing this
yourself), <code class="prettyprint">NSLog</code> will post a
message to the system log with the <code><Warning></code>
priority.
</p>
<p>
<a href="http://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/LoggingErrorsAndWarnings.html#//apple_ref/doc/uid/10000172i-SW8-SW3">Apple's
description of the various logging levels</a> describes a warning as meaning:
</p>
<blockquote>
<p>
Something is amiss and might fail if not corrected.
</p>
</blockquote>
<p>
This isn't what we want for our debug messages. If we read a little
further in the documentation, Apple gives us
their <a href="http://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/LoggingErrorsAndWarnings.html#//apple_ref/doc/uid/10000172i-SW8-SW7">logging
best-practices</a>. It's worth reading it all if you have the time:
</p>
<blockquote>
<h2>Adopt Best Practices for Logging</h2>
<p>
Treat your log messages as a potentially customer-facing portion of
your application, not as purely an internal debugging tool. Follow
good logging practices to make your logs as useful as possible:
</p>
<ul>
<li>Provide the right amount of information; no more, no less. Avoid creating clutter.</li>
<li>Avoid logging messages that the user can't do anything about.</li>
<li>Use hashtags and log levels to make your log messages easier to search and filter.</li>
</ul>
<p>
In order for the log files to be useful (to developers and users),
they must contain the right level of detail. If applications log
too much, the log files quickly fill up with uninteresting and
meaningless messages, overwhelming any useful content. If they log
too little, the logs lack the details needed to identify and
diagnose issues.
</p>
<div class="blockquote-note" style="text-align: center;">
<p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTsnLoTpobwZbfmbJwOHBQrzdzylvYSpSlLPrSK4SdrGtJ22FvZ3y0SKmg9WlN-RLpWhpJi7_dbT-DjwfzPm2tXGLTeyKwdhqlpON9lhATEgsUkrXZ6Kj26isYw5vyXYhVMQ3xnUM4Kp6p/s1600/kitten-sweater.jpg"
alt="Picture of a cute cat in a knitted sweater"
style="height:345; width: 400px" />
</p>
<footnote>
<p>
It's at this point that you probably got tired of reading this
excerpt. So here's a cute picture of a kitten to keep you
going.
</p>
<p>
If you looked ahead and got distracted by the kitten, I
apologize.
</p>
</footnote>
</div>
<p>
Logging excessively makes the log files much harder to use, and
decreases the value of the logs to your user (who can't easily
find the important log messages), to you (who can't easily use the
log messages to aid in debugging), and to other developers (whose
applications' log messages are buried under yours).
</p>
<p>
[...]
</p>
<!--
<p>
You should avoid writing your own log files. Using the APIs
instead of creating your own logging system is the recommended
best practice, and provides several advantages:
</p>
<ul>
<li>Your log messages are easier to find—users only have to look in one place.</li>
<li>The system doesn't get cluttered with numerous log files from different programs.</li>
<li>The logging APIs manage log rotation and filtering for you.</li>
<li>The logging APIs allow you to search logs as well as log messages.</li>
</ul>
-->
<p>
If you log debugging information, you should either disable these
messages by default or log them at the Debug level. This ensures
that your debugging messages don't clutter up your (and your
users') logs.
</p>
</blockquote>
<p>
So you kinda get the feeling that this stuff applies more to the
desktop than a mobile device, right? Wrong. We're professionals,
and it's clear we need a better solution
than <code class="prettyprint">NSLog</code>. Even the kitten agrees.
<h2>Quick and Dirty</h2>
<p>One quick and dirty way to improve things is to write a custom
logging macro that will still
use <code class="prettyprint">NSLog</code>, but that turns into a
NOP during a release build:
</p>
<div class="code">
<pre class="prettyprint">
#ifdef NDEBUG
// do nothing
#define MyLog(...)
#else
#define MyLog NSLog
#endif
</pre>
</div>
<p>
<code class="prettyprint">NDEBUG</code> is a standard macro that means "no
debug" or "release mode". This will usually be defined in the
Release configuration of your target's build settings.
</p>
<p>
With this little snippet of code we get a
new <code class="prettyprint">MyLog</code> macro which is a simple
alias to <code class="prettyprint">NSLog</code> when debugging, and
which will turn into a no-op in our release builds. For genuine
error conditions, we can stick
with <code class="prettyprint">NSLog</code> and the error output
will always be sent to the device log. Hurrah!
</p>
<p>
There's one niggling detail, though. Our debug statements and our
error messages are both going to be logged with
the <code><Warning></code> priority. What the
hell, <code class="prettyprint">NSLog</code>? And I thought the documentation said you were supposed to
log <em>errors</em>, not warnings. Just who the hell do you think you are?
</p>
<p>
This doesn't sit right with me. This doesn't sit right with
me <em>at all</em>. I want to see <code><Debug></code>
and <code><Error></code> in my logs, gosh-darn-it.
</p>
<h2>The Apple System Log facility</h2>
<p>
So Apple has just been telling us that we should use <em>the
APIs™</em> and that we get a bunch of awesome advantages when
doing so. The API that Apple is referring to is the Apple System Log
facility, or <abbr>ASL</abbr>.
</p>
<p>
Now it's at this point that some people would jump into a well
thought-out introduction to the Apple System Log: its history, how
it works, and maybe a few flow diagrams. I'm too lazy for that right
now, so I'm just going to show you this "Hello, World!" example from
the <a href="http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/asl.3.html">asl
man pages</a>:
</p>
<div class="code">
<pre class="prettyprint">
#include <asl.h>
// ...
asl_log(NULL, NULL, ASL_LEVEL_INFO, "Hello World!");
</pre>
</div>
<p>
OK, so we include a
header... call <code class="prettyprint">asl_log</code>... ignore a
bunch of arguments we aren't interested in, and- oh hey, look. We
can specify a logging level. Neat.
</p>
<p>
ASL has a lot of features, but all we're interested today is
creating a bunch of simple logging functions so we can distinguish
between debug messages, errors, warnings, natural disasters, etc. We
aren't going to worry about fancy features like logging to custom
files or network sockets.
</p>
<p>
If we use <code class="prettyprint">asl_log</code> as in the above
code sample (with the first argument as NULL), we get a simple
thread-safe way (albeit through locking) to log messages to the
system log at different levels.
</p>
<p>
The full list of log levels can be found
in <code class="prettyprint">asl.h</code>. I've listed these below,
along
with <a href="http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/LoggingErrorsAndWarnings.html#//apple_ref/doc/uid/10000172i-SW8-SW1">the
corresponding descriptions from Apple's guidelines</a>:
</p>
<dl>
<dt><code>ASL_LEVEL_EMERG</code></dt>
<dd>The highest priority, usually reserved for catastrophic failures and reboot notices.</dd>
<dt><code>ASL_LEVEL_ALERT</code></dt>
<dd>A serious failure in a key system.</dd>
<dt><code>ASL_LEVEL_CRIT</code></dt>
<dd>A failure in a key system.</dd>
<dt><code>ASL_LEVEL_ERR</code></dt>
<dd>Something has failed.</dd>
<dt><code>ASL_LEVEL_WARNING</code></dt>
<dd>Something is amiss and might fail if not corrected.</dd>
<dt><code>ASL_LEVEL_NOTICE</code></dt>
<dd>Things of moderate interest to the user or administrator.</dd>
<dt><code>ASL_LEVEL_INFO</code></dt>
<dd>The lowest priority that you would normally log, and purely informational in nature.</dd>
<dt><code>ASL_LEVEL_DEBUG</code></dt>
<dd>The lowest priority, and normally not logged except for messages from the kernel.</dd>
</dl>
<p>
This is looking more and more like the typical logging frameworks we
see on other platforms.
</p>
<p>
By default, ASL will only record messages at
priority <code class="prettyprint">ASL_LEVEL_NOTICE</code> and
above. This means that although we will be using the ASL system, our
debug messages will <em>not</em> be visible in the device logs by
default. This is good, but it's still a good idea to turn our debug
statements into no-ops in a release build. One reason is
performance: we don't want logging commands to affect performance
sensitive areas of our code.
</p>
<h2>Getting down to it</h2>
<p>
So with all that out of the way, we can begin to implement some new
logging macros using the ASL API.
</p>
<p>
The first thing we'll do is define a macro which will let us
compile-out log statements at a certain level when in release mode:
</p>
<div class="code">
<pre class="prettyprint">
#ifndef MW_COMPILE_TIME_LOG_LEVEL
#ifdef NDEBUG
#define MW_COMPILE_TIME_LOG_LEVEL ASL_LEVEL_NOTICE
#else
#define MW_COMPILE_TIME_LOG_LEVEL ASL_LEVEL_DEBUG
#endif
#endif
</pre>
</div>
<p>
When we are in release mode the default compile-time log level will
be <code class="prettyprint">ASL_LEVEL_NOTICE</code>. We want
messages at "notice" and above to be sent to the system log, and
everything else to be completely compiled out of our code by the
preprocessor. We'll see how this is done in a moment.
</p>
<p>When we are in debug mode, the log level will
be <code class="prettyprint">ASL_LEVEL_DEBUG</code> so messages at
"debug" and above (i.e. all messages) will be compiled into our
code.
</p>
<p>We can also override the default value
of <code class="prettyprint">MW_COMPILE_TIME_LOG_LEVEL</code> with
custom compiler flags in our application's build settings. This lets
us control the log level for different targets and configurations.
</p>
<p>
Next we define macros for each log level that we want to
support. Starting with the "emergency" level we get:
</p>
<div class="code">
<pre class="prettyprint">
#if MW_COMPILE_TIME_LOG_LEVEL >= ASL_LEVEL_EMERG
void MWLogEmergency(NSString *format, ...);
#else
#define MWLogEmergency(...)
#endif
</pre>
</div>
<p>
If the "emergency" log level is allowed by the value
in <code class="prettyprint">MW_COMPILE_TIME_LOG_LEVEL</code>, we
define a typical log function which accepts a format string and
arguments. Otherwise we turn it into a no-op and the statement will
get compiled away by the preprocessor.
</p>
<p>
We repeat similar code for each of the different log levels:
</p>
<div class="code">
<pre class="prettyprint">
#if MW_COMPILE_TIME_LOG_LEVEL >= ASL_LEVEL_ALERT
void MWLogAlert(NSString *format, ...);
#else
#define MWLogAlert(...)
#endif
//
// ... SNIP ...
//
#if MW_COMPILE_TIME_LOG_LEVEL >= ASL_LEVEL_DEBUG
void MWLogDebug(NSString *format, ...);
#else
#define MWLogDebug(...)
#endif
</pre>
</div>
<p>
Next we write the implementations for all of these functions. We can
use some more macro hackery to avoid duplicated code. In small
confined situations like this, macros actually <em>aren't</em> pure
evil:
</p>
<div class="code">
<pre class="prettyprint">
#define __MW_MAKE_LOG_FUNCTION(LEVEL, NAME) \
void NAME (NSString *format, ...) \
{ \
va_list args; \
va_start(args, format); \
NSString *message = [[NSString alloc] initWithFormat:format
arguments:args]; \
asl_log(NULL, NULL, (LEVEL), "%s", [message UTF8String]); \
va_end(args); \
}
__MW_MAKE_LOG_FUNCTION(ASL_LEVEL_EMERG, MWLogEmergency)
__MW_MAKE_LOG_FUNCTION(ASL_LEVEL_ALERT, MWLogAlert)
__MW_MAKE_LOG_FUNCTION(ASL_LEVEL_CRIT, MWLogCritical)
__MW_MAKE_LOG_FUNCTION(ASL_LEVEL_ERR, MWLogError)
__MW_MAKE_LOG_FUNCTION(ASL_LEVEL_WARNING, MWLogWarning)
__MW_MAKE_LOG_FUNCTION(ASL_LEVEL_NOTICE, MWLogNotice)
__MW_MAKE_LOG_FUNCTION(ASL_LEVEL_INFO, MWLogInfo)
__MW_MAKE_LOG_FUNCTION(ASL_LEVEL_DEBUG, MWLogDebug)
#undef __MW_MAKE_LOG_FUNCTION
</pre>
</div>
<p>
If we expand out one of the macro invocations we can see what is
generated for the <code class="prettyprint">MWLogDebug</code>
function:
</p>
<div class="code">
<pre class="prettyprint">
void MWLogDebug (NSString *format, ...)
{
va_list args;
va_start(args, format);
NSString *message = [[NSString alloc] initWithFormat:format
arguments:args];
asl_log(NULL, NULL, (ASL_LEVEL_DEBUG), "%s", [message UTF8String]);
va_end(args);
}
</pre>
</div>
<p>
This is pretty straight forward. Note that by passing
a <code class="prettyprint">NULL</code> client as the first argument
to <code class="prettyprint">asl_log</code> we get the default concurrency behaviour:
</p>
<blockquote>
Multiple threads may log messages safely using a NULL aslclient
argument, but the library will use an internal lock, so that in fact
only one thread will log at a time.
</blockquote>
<p>
For a simple <code>NSLog</code> replacement, this fine. If you
wished, you could create a new client for each thread that you
encounter, although managing the lifetime of this object might be a
little tricky.
</p>
<p>
OK, we're almost done. I mentioned that by default, messages below
the "notice" level will not be visible in the system
log. Additionally, if we tried using the <code>MWLogDebug</code> as
it is now, we wouldn't see anything in the debug console.
</p>
<p>
Fortunately ASL let's us send our messages to additional file
descriptors. If we add the <code>STDERR</code> file descriptor to
the logging facility, we'll be able to see our messages in the
debugger:
</p>
<div class="code">
<pre class="prettyprint">
asl_add_log_file(NULL, STDERR_FILENO);
</pre>
</div>
<p>
We only need to call this once, so with the help of
GCD's <code class="prettyprint">dispatch_once</code> we'll add the
following function to our implementation file:
</p>
<div class="code">
<pre class="prettyprint">
static void AddStderrOnce()
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
asl_add_log_file(NULL, STDERR_FILENO);
});
}
</pre>
</div>
...and then modify our logging function to call it:
<div class="code">
<pre class="prettyprint">
#define __MW_MAKE_LOG_FUNCTION(LEVEL, NAME) \
void NAME (NSString *format, ...) \
{ \
<span class="highlight">AddStderrOnce();</span> \
va_list args; \
va_start(args, format); \
NSString *message = [[NSString alloc] initWithFormat:format arguments:args]; \
asl_log(NULL, NULL, (LEVEL), "%s", [message UTF8String]); \
va_end(args); \
}
</pre>
</div>
<p>
And we're done. We can now test this stuff out. If we run the
following code:
</p>
<div class="code">
<pre class="prettyprint">
MWLogError(@"This is an error");
MWLogDebug(@"This is a debug statement");
MWLogWarning(@"This is a warning");
</pre>
</div>
<p>
We'll see this in our device log:
</p>
<pre>
Example[12268] <Error>: This is an error
Example[12268] <Warning>: This is a warning
</pre>
<p>
And we'll see this in our debug console:
</p>
<pre>
Example[12268] <Error>: This is an error
Example[12268] <Debug>: This is a debug statement
Example[12268] <Warning>: This is a warning
</pre>
<p>
Each message is marked with the appropriate level, and the debug
message is only output to the debug console, not the device log. If
you <em>do</em> want to change the level at which messages are sent
to the device log, you can call
the <code class="prettyprint">asl_set_filter</code> function with an
appropriate mask like this:
</p>
<div class="code">
<pre class="prettyprint">
asl_set_filter(NULL, ASL_FILTER_MASK_UPTO(ASL_LEVEL_DEBUG));
</pre>
</div>
<p>
After calling this, <em>all</em> messages (including at
the <code>DEBUG</code> level) will be sent to the device log.
</p>
<p>
So after all that, we've implemented a very simple alternative
to <code class="prettyprint">NSLog</code> which uses the standard
Apple System Log facility, and ensures your debug messages will not
appear in customer device logs.
</p>
<p>You can find
the <a href="http://github.com/MikeWeller/MWLogging">source code at
github</a> which you can use without restriction.
</p>
<h2>Working more efficiently by using Breakpoints</h2>
<p style="float: right;">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPfHv3Vip3EvBF9Q_645gDTrAVYNLB_LxaliN8Rqv9F_l4tH12mxIZZkotdU_O35vyLEszUnkAkUZKHLPCGGowZF38X9deKDaptTS4gpMvn5MiWXGuW3tyUkrTATPHa8NtjH0Jg1CSSy8v/s1600/Screen+Shot+2012-07-04+at+10.53.25.png" alt="Screenshot of a breakpoint with a log command" />
</p>
<p>
Now that we've got our brand-spanking-new logging functions, I'd
like to take a few moments to discuss efficiency.
</p>
<p>
Think about how much time you waste every day writing debug
statements in code. Imagine you are looking at your app running on a
device, and you want to examine the value of a variable or see how
it changes over time.
</p>
<p>We all <em>know</em> the debugger can do this for us, but it's so
easy to revert to bad habits and write a log statement
instead. Think about the steps involved. You have to stop your
running app, write some code
like <code class="prettyprint">MWLogDebug(@"myValue is now %@",
myValue)</code>, recompile, run your app again, and then navigate
back to the view that triggers the code.
</p>
<p>
This isn't a huge amount of time when you look at just one
instance. But over the course of an entire day, week, or year, this
edit/compile/debug cycle is wasting a huge amount of your
development time.
</p>
<p>
There is a far more efficient way to get this kind of information,
without stopping your app, by using breakpoints. I would highly
recommend you
watch <a href="https://developer.apple.com/videos/wwdc/2012/?include=412#412">Session
412 - Debugging in Xcode</a> from WWDC 2012 for more information
about this. If you aren't using breakpoints in your day-to-day
development, you should really watch this video.
</p>
<h2>Comments?</h2>
<p>
So that rounds up the first post of this series. If you have
comments or suggestions please use the form below or email me.
</p>Unknownnoreply@blogger.com54tag:blogger.com,1999:blog-5863548874298958343.post-87501770455525859152012-07-09T22:52:00.001+02:002012-07-09T22:54:54.718+02:00You're Doing It Wrong #0: Introduction<p>
Hi there. I've started this blog so I can post articles on iOS development.
</p>
<p>
I've been developing for the iOS platform for a few years now, and though I'm still learning new things every day I feel like it's time I shared some of the things I've learnt.
</p>
<p>
The general theme is "You're Doing It Wrong", and each post will tackle one of the many anti-patterns or bad practices that I've witnessed over the years, and hopefully provide you with a better solution.
</p>
<p>
I will be updating this post with links to each entry as they are published. Stay tuned.
</p>
<p>
The posts so far:
</p>
<ul>
<li><a href="http://doing-it-wrong.mikeweller.com/2012/07/youre-doing-it-wrong-1-nslogdebug-ios.html">You're Doing It Wrong #1: NSLog("Debug");</a></li>
</ul>Unknownnoreply@blogger.com10