<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Tewha.net</title>
    <link>https://tewha.net/tags/os-x-development/</link>
    <description>Recent content on Tewha.net</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Wed, 06 Mar 2013 16:00:00 +0000</lastBuildDate>
    <atom:link href="https://tewha.net/tags/os-x-development/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Check your thread</title>
      <link>https://tewha.net/2013/03/check-your-thread/</link>
      <pubDate>Wed, 06 Mar 2013 16:00:00 +0000</pubDate>
      <guid>https://tewha.net/2013/03/check-your-thread/</guid>
      <description>&lt;p&gt;When you start using Grand Central Dispatch or &lt;code&gt;NSOperation&lt;/code&gt;, you’ll want to perform some actions on the main thread and some intentionally off the main thread.&lt;/p&gt;
&lt;p&gt;This is a simple and obvious technique, but it took me a while to adopt it: You can do by asserting with &lt;code&gt;NSAssert&lt;/code&gt; or &lt;code&gt;NSCAssert&lt;/code&gt; for &lt;code&gt;[NSThread isMainThread]&lt;/code&gt;, just as you would assert any other condition.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>When you start using Grand Central Dispatch or <code>NSOperation</code>, you’ll want to perform some actions on the main thread and some intentionally off the main thread.</p>
<p>This is a simple and obvious technique, but it took me a while to adopt it: You can do by asserting with <code>NSAssert</code> or <code>NSCAssert</code> for <code>[NSThread isMainThread]</code>, just as you would assert any other condition.</p>
<p>Like this:</p>
<pre><code>- (void)updateUI {
    NSAssert([NSThread isMainThread], @&quot;Only update UI from main thread&quot;);
    // update UI
}

- (void)backgroundWork {
    NSAssert(![NSThread isMainThread], @&quot;Only do work off main thread&quot;);
    // do work
}
</code></pre>
<p>With assertions like this in place, you’ll sort out what executes where in short order.</p>
<p>I wish I had done this to my code right away; it’s much simpler to get it right than to go back and fix it all later.</p>]]></content:encoded>
    </item>
    <item>
      <title>Presenting BlockAssert</title>
      <link>https://tewha.net/2013/02/presenting-blockassert/</link>
      <pubDate>Fri, 22 Feb 2013 16:00:00 +0000</pubDate>
      <guid>https://tewha.net/2013/02/presenting-blockassert/</guid>
      <description>&lt;p&gt;Assertions are a great tool. As an Objective-C programmer, I use &lt;code&gt;NSAssert&lt;/code&gt; and &lt;code&gt;NSCAssert&lt;/code&gt; liberally.&lt;/p&gt;
&lt;p&gt;For various reasons, you sometimes can’t use &lt;code&gt;NSAssert&lt;/code&gt; in a block easily. I’m going to explain why and describe a new macro, &lt;code&gt;BlockAssert&lt;/code&gt;, which solves this.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>Assertions are a great tool. As an Objective-C programmer, I use <code>NSAssert</code> and <code>NSCAssert</code> liberally.</p>
<p>For various reasons, you sometimes can’t use <code>NSAssert</code> in a block easily. I’m going to explain why and describe a new macro, <code>BlockAssert</code>, which solves this.</p>
<h2 id="background">Background</h2>
<p>An assertion is a predicate (a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place. (Source: <a href="http://en.wikipedia.org/wiki/Assertion_(computing)">Wikipedia</a>.)</p>
<p><code>NSAssert</code> and <code>NSCAssert</code> are Foundation’s assertion macros. They’re kind of like C’s assert macro, but provide an error message in the same form as <code>NSLog</code>. The difference between them is that <code>NSAssert</code> references <code>self</code>, which is only defined for Objective-C methods. <code>NSCAssert</code>, then, is <code>NSAssert</code> for C functions.</p>
<p>Blocks are often defined in Objective-C methods, but they’re not themselves Objective-C methods. Although they’re actually implemented as objects of their own, the syntax is more like a C functions. They don’t define self, though anything you want from the method scope are captured strongly into the block expression. This means that if you use <code>NSAssert</code> you’ll be capturing <code>self</code>. But that strong reference can cause a circular reference.</p>
<p>A circular reference is formed the block owns the object and the object owns something that owns the block. None of the memory will ever be cleaned up. Even you <em>do</em> clean up the memory, you’ll get a compiler warning that you need to ignore.</p>
<p>Rather than sort out which of these compiler warnings is valid, a lot of people use this pattern:</p>
<pre><code>__weak typeof(self) weakSelf = self;
foo.completionBlock = ^{
	__strong typeof(self) strongSelf = weakSelf;
    [strongSelf doSomething];
};
</code></pre>
<p>This breaks the circular reference, and because we’ve used <code>__weak</code> we’re assured that <code>weakSelf</code> is not a dangling pointer. If <code>self</code> no longer exists, <code>weakSelf</code> is <code>nil</code>. Reassigning back to a <code>__strong</code> variable presents the variable from being deallocated</p>
<p><em>In this case, it’s not actually necessary to assign <code>weakSelf</code> to a <code>__strong</code> variable. The recipient of a message won’t be deallocated until the message returns. However, if you are doing multiple things with <code>weakSelf</code> — such as doing assertions against it and sending it a message — it could become deallocated between those messages.</em></p>
<p>The catch? <code>NSAssert</code> still uses the <code>self</code> variable by name. This led to an interesting question on StackOverflow about <a href="http://stackoverflow.com/questions/14194600/is-typeofself-self-weakself-construction-legitimate-inside-block">defining a block-scope self</a>, a technique that’s valid but requires you to remember to do it every time and <a href="/2013/02/against-gcc_warn_shadow/">causes a warning if GCC_WARN_SHADOW is on</a>.</p>
<h2 id="a_new_assertion_macro">A new assertion macro</h2>
<p>In the past, I’ve mostly done avoided this by not using assertions in blocks. You don’t need them very often, as you can usually do your assertions in the method’s scope. But inspired by that question, I’ve found a better way: I define my own assertion macro.</p>
<p>I have several such macros I define, in a single file that’s imported in as part of my precompiled header.</p>
<p>The macro looks like this:</p>
<pre><code>#define BlockAssert(condition, desc, ...) 
    do { 
        __PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS 
        if (!(condition)) { 
            [[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd 
            object:strongSelf file:[NSString stringWithUTF8String:__FILE__] 
                lineNumber:__LINE__ description:(desc), ##__VA_ARGS__]; 
        } 
        __PRAGMA_POP_NO_EXTRA_ARG_WARNINGS 
    } while(0)
</code></pre>
<p>This is basically a copy-paste of <code>NSAssert</code>, but uses <code>strongSelf</code> instead of <code>self</code>. (Note, however, that we have <em>not</em> pretended to be part of Foundation by using a NS prefix.)</p>
<p>To use <code>BlockAssert</code>, you need to use the <code>weakSelf = self; strongSelf = weakSelf;</code> pattern, but you probably already are. And if not, the compiler will throw an error: <strong>Use of undeclared identifier: ‘strongSelf’</strong>. You can either adopt <code>strongSelf</code> or switch over to <code>NSAssert</code>.</p>
<p>For example:</p>
<pre><code>- (IBAction)clickButton: (UIButton *)sender {
    sender.disabled = YES;
    [self performActionWithCompletion: ^{
        BlockAssert(state, @&quot;Invalid state&quot;);
        sender.disabled = NO;
    }];
}
</code></pre>
<h2 id="conclusion">Conclusion</h2>
<p>I think this is a pretty good approach: If you use <code>NSAssert</code> where you meant to use <code>BlockAssert</code> and it matters, you’ll get a warning about a potential circular reference. If you use <code>BlockAssert</code> where you meant to use <code>NSAssert</code>, you’ll probably get a compiler error.</p>]]></content:encoded>
    </item>
    <item>
      <title>Make your library enforce ARC</title>
      <link>https://tewha.net/2012/09/make-your-library-enforce-arc/</link>
      <pubDate>Thu, 27 Sep 2012 14:00:00 +0000</pubDate>
      <guid>https://tewha.net/2012/09/make-your-library-enforce-arc/</guid>
      <description>&lt;p&gt;If you have an open source library that requires Automatic Reference Counting (ARC), you may have issues with your users trying to build it without ARC turned on. Luckily, it’s pretty simple to &lt;em&gt;enforce&lt;/em&gt; ARC.&lt;/p&gt;
&lt;p&gt;I’m going to discuss how to do so, and why it’s a good idea.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>If you have an open source library that requires Automatic Reference Counting (ARC), you may have issues with your users trying to build it without ARC turned on. Luckily, it’s pretty simple to <em>enforce</em> ARC.</p>
<p>I’m going to discuss how to do so, and why it’s a good idea.</p>
<p>Here’s an example, which I submitted to AFNetworking:</p>
<pre><code>#if !__has_feature(objc_arc)
#error AFNetworking must be built with ARC.
// You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files.
#endif
</code></pre>
<p>When the user builds the unit, the error will be highlighted. They’ll see the comment just below, explaining how to resolve the problem.</p>
<p>Adding it to every .m file may seem overkill, but there’s two good reasons for this:</p>
<ol>
<li>No matter which file gets compiled first an error will top the list instead of warnings. It’s sufficient to add it only to a central file, but you’ll probably still get support requests that way. You’re better off adding it everywhere; this is all about reducing your work.</li>
<li>ARC can be decided on a per-file basis. If you include it in only one file, the user may add -fobjc-arc to just that one file!</li>
</ol>
<p>But do not add this to your headers. Even if your code requires ARC, there’s no reason to require that the user’s code also use ARC. Apple did the right thing here.</p>]]></content:encoded>
    </item>
    <item>
      <title>Objective-C Feature Availability Index</title>
      <link>https://tewha.net/2012/09/objective-c-feature-availability-index/</link>
      <pubDate>Tue, 18 Sep 2012 14:00:00 +0000</pubDate>
      <guid>https://tewha.net/2012/09/objective-c-feature-availability-index/</guid>
      <description>&lt;p&gt;Which modern Objective-C feature can you use where? Check the &lt;a href=&#34;http://developer.apple.com/library/ios/releasenotes/ObjectiveC/ObjCAvailabilityIndex/_index.html&#34;&gt;Objective-C Feature Availability Index&lt;/a&gt; (via &lt;a href=&#34;https://twitter.com/0xced/statuses/248017993903267841&#34;&gt;0xced&lt;/a&gt;).&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>Which modern Objective-C feature can you use where? Check the <a href="http://developer.apple.com/library/ios/releasenotes/ObjectiveC/ObjCAvailabilityIndex/_index.html">Objective-C Feature Availability Index</a> (via <a href="https://twitter.com/0xced/statuses/248017993903267841">0xced</a>).</p>
]]></content:encoded>
    </item>
    <item>
      <title>ADC incidents</title>
      <link>https://tewha.net/2012/09/adc-incidents/</link>
      <pubDate>Mon, 10 Sep 2012 14:00:00 +0000</pubDate>
      <guid>https://tewha.net/2012/09/adc-incidents/</guid>
      <description>&lt;p&gt;In the past, I’ve tried to avoid using ADC incidents. You get two a year per program, and most years I’ve avoided using any. This year, I decided to use them both the iOS ones up before renewing.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>In the past, I’ve tried to avoid using ADC incidents. You get two a year per program, and most years I’ve avoided using any. This year, I decided to use them both the iOS ones up before renewing.</p>
<p>The first one was clarification on how to fix a bug demonstrated by some Apple sample code. I got a response, but it wasn’t especially satisfying. But that’s okay, because in the end I found a way to do a different UI and avoid the bug entirely. Let’s call it a draw.</p>
<p>The second one, however, was a mistake in how I was using UIKit that I didn’t realize was a mistake. I boiled it down to a <a href="https://github.com/tewha/ExtraGridLines">test case</a> and submitted the project to Apple. As part of solving the incident, Apple not only explained what I was doing wrong, but provided snippets of code that would work.</p>
<p>This would be gold, but they also fully corrected my code the code I’d sent.</p>
<p>Of course, when I tried to integrate the solution back into my real application, I ran into other problems. However, the explanation Apple had offered me was enough that I was able to solve those other problems, too.</p>
<p>Basically, I got a fantastic code review out of that DTS incident by someone who clearly knows iOS and UIKit better than I ever will. Total win.</p>
<p>I don’t plan on wasting these in the future, but neither will I horde them in case of emergency. They’re worth using for the really nasty problems, and they’re not incredibly expensive to replace — $99 buys another two incidents.</p>]]></content:encoded>
    </item>
    <item>
      <title>Wireless proxies may re-compress your files</title>
      <link>https://tewha.net/2012/06/wireless-proxies-may-re-compress-your-files/</link>
      <pubDate>Thu, 07 Jun 2012 14:00:00 +0000</pubDate>
      <guid>https://tewha.net/2012/06/wireless-proxies-may-re-compress-your-files/</guid>
      <description>&lt;p&gt;If you’re downloading a file with widely-recognized lossy compression, your user’s cellular provider may interfere with it. This has always been true of internet connections; I first ran into this with dialup years ago. But it went away for a while with broadband, is back with wireless.&lt;/p&gt;
&lt;p&gt;The simplest example is a JPEG. You may get the JPEG you expect, but it’s also possible for the proxy to deliver a smaller JPEG than you expect. The cell provider considers it “close enough”, and the doubly-compressed JPEG is smaller (and far uglier).&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>If you’re downloading a file with widely-recognized lossy compression, your user’s cellular provider may interfere with it. This has always been true of internet connections; I first ran into this with dialup years ago. But it went away for a while with broadband, is back with wireless.</p>
<p>The simplest example is a JPEG. You may get the JPEG you expect, but it’s also possible for the proxy to deliver a smaller JPEG than you expect. The cell provider considers it “close enough”, and the doubly-compressed JPEG is smaller (and far uglier).</p>
<p>This may be true of other file types as well, if they’re commonly recognized as lossy and computationally easy to re-compress.</p>
<p>I have read reports of T-Mobile and O2 doing this. I think it’s been noted with other cell providers, too.</p>
<p>There’s two possible fixes:</p>
<ul>
<li>Switching to HTTPS will fix this problem as the proxy will no longer be in the middle of the communication. If your resource is available via HTTPS, this is a fantastic and simple fix.</li>
<li>Add a HTTP header to defeat this. The idea is to add a no-transform cache-control HTTP header to your request. This should disallow the server from making this kind of change. See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.5">RFC 2616, section 14.9.5</a>.</li>
</ul>
<p><em>Thanks to <a href="http://www.tonymillion.com">Tony Milllion</a> for pointing out the HTTPS solution, and letting me know it affected O2 as well.</em></p>]]></content:encoded>
    </item>
    <item>
      <title>AFNetworking: a well managed open source project</title>
      <link>https://tewha.net/2012/06/afnetworking-a-well-managed-open-source-project/</link>
      <pubDate>Wed, 06 Jun 2012 14:00:00 +0000</pubDate>
      <guid>https://tewha.net/2012/06/afnetworking-a-well-managed-open-source-project/</guid>
      <description>&lt;p&gt;Last week, I talked about &lt;a href=&#34;https://tewha.net/2012/06/networking-using-nsurlconnection&#34;&gt;Networking using NSURLConnection&lt;/a&gt;. In a future post, I’m going to talk about how to use AFNetworking. But first, I wanted to talk about why you should trust AFNetworking as a project in your project.&lt;/p&gt;
&lt;p&gt;I haven’t been using github for long. That said, AFNetworking is the best-managed git project I’ve seen. It’s being managed so well that I wanted to write about it. In doing so, I’m not trying to praise Mattt Thompson’s efforts. It will probably come across that way, and he deserves it. Instead, I want to say that if you plan to maintain a git project, you should handle it as well as Mattt does.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>Last week, I talked about <a href="/2012/06/networking-using-nsurlconnection">Networking using NSURLConnection</a>. In a future post, I’m going to talk about how to use AFNetworking. But first, I wanted to talk about why you should trust AFNetworking as a project in your project.</p>
<p>I haven’t been using github for long. That said, AFNetworking is the best-managed git project I’ve seen. It’s being managed so well that I wanted to write about it. In doing so, I’m not trying to praise Mattt Thompson’s efforts. It will probably come across that way, and he deserves it. Instead, I want to say that if you plan to maintain a git project, you should handle it as well as Mattt does.</p>
<h2 id="codebase">Codebase</h2>
<p>AFNetworking is, ultimately, a simple library. It has only a few classes, and reuses lots of the sane bits of iOS frameworks. Its main class is <code>AFURLConnectionOperation</code>, which encapsulates a <code>NSURLConnection</code> and its delegate methods in a subclass of <code>NSOperation</code>.</p>
<p>Without going into the gory details of Foundation framework classes, this is how iOS networking <strong>should</strong> work. Of course, you could get into a lot of trouble even with the right fundamentals. But AFNetworking doesn’t. It’s ten source files with headers, and one header to rope it all together.</p>
<h2 id="issues">Issues</h2>
<p>As I write this, AFNetworking has 368 closed issues. 358 of them are closed. Alone, this tells you something: He responds to issues.</p>
<p>But if you watch how he handles issues, you’ll see qualities to which all developers should aspire:</p>
<ol>
<li>Patience.</li>
<li>Humility.</li>
</ol>
<p>His responses are available to everyone, of course. I came to appreciate how well Mattt was running the project by reading these. Along the way, I learned a lot about AFNetworking.</p>
<h2 id="pull_requests">Pull requests</h2>
<p>I have no idea what percentage of the code Mattt has written, vs. code brought in by other contributors. I can tell you that at the moment, AFNetworking has 99 pull requests total. 98 of these are closed. Whether they were merged or not, he’s dealt with them.</p>
<p>Some of these pull requests are pretty mundane. I’ve landed three myself, all very small and ordinary. However, in each case Mattt not only merged the request, but thanked me for it and explained what had happened. The thanks are appreciated. The explanation isn’t necessary, but gives me a better feeling of connectedness.</p>
<p>For the pull request that he <strong>didn’t</strong> accept, he explained what I was doing wrong (gently and politely), and provided me with an alternative that actually worked better than the pull request I’d made.</p>
<p>Looking through a few pull requests, I don’t see anything unusual about the way he treated me.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Look, I’m not saying Mattt Thompson is handling AFNetworking perfectly. That’d be impossible to prove, and you could probably prove otherwise pretty quickly. But he’s handling it <strong>well</strong>.</p>
<p>I’m also not going to claim the code is perfect. The library actually swizzles itself, which is one of the craziest things I’ve seen. But the craziness is localized to a small section of code, and minor overall.</p>
<p>I’m feeling connected to the project, I’m feeling confident, and I’m learning more about it. Even the bits I don’t care about yet. And if that isn’t a successful open source project, I’m not sure what is.</p>]]></content:encoded>
    </item>
    <item>
      <title>Using blocks to handle errors</title>
      <link>https://tewha.net/2012/06/using-blocks-to-handle-errors/</link>
      <pubDate>Tue, 05 Jun 2012 14:00:00 +0000</pubDate>
      <guid>https://tewha.net/2012/06/using-blocks-to-handle-errors/</guid>
      <description>&lt;p&gt;In the past, I’ve talked about &lt;a href=&#34;https://tewha.net/2011/07/blocks-to-remove-redundancy/&#34;&gt;Using blocks to remove redundancy&lt;/a&gt;. But now I want to explain the pattern I’ve adopted since, which is my favorite block pattern of all. Even though it, too, is all about removing redundancy: handling errors.&lt;/p&gt;
&lt;p&gt;Although Objective-C supports exceptions, they’re not commonly used. A thrown exception is usually not caught, making it a fatal error.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>In the past, I’ve talked about <a href="/2011/07/blocks-to-remove-redundancy/">Using blocks to remove redundancy</a>. But now I want to explain the pattern I’ve adopted since, which is my favorite block pattern of all. Even though it, too, is all about removing redundancy: handling errors.</p>
<p>Although Objective-C supports exceptions, they’re not commonly used. A thrown exception is usually not caught, making it a fatal error.</p>
<p><a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocExceptionHandling.html#//apple_ref/doc/uid/TP30001163-CH13-TPXREF168">The Objective-C Programming Language</a> describes it thus:</p>
<blockquote>
<p><strong>Important</strong> In many environments, use of exceptions is fairly commonplace. For example, you might throw an exception to signal that a routine could not execute normally—such as when a file is missing or data could not be parsed correctly. Exceptions are resource-intensive in Objective-C. You should not use exceptions for general flow-control, or simply to signify errors. Instead you should use the return value of a method or function to indicate that an error has occurred, and provide information about the problem in an error object. For more information, see <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/ErrorHandling/ErrorHandling.html#//apple_ref/doc/uid/TP40001806">Error Handling Programming Guide</a>.</p>
</blockquote>
<p>What, then, is the usual pattern for handling non-fatal errors. The answer is the <code>NSError class</code>, along with a few simple conventions:</p>
<ol>
<li>Any method that can fail should return 0 (or an equivalent) on failure.</li>
<li>Any method that fails by returning 0 (or an equivalent) on failure should take a pointer to return a <code>NSError</code> instance, which it populates with error details.</li>
<li>If the error pointer is <code>NULL</code>, the method should not return an error.</li>
</ol>
<p>For instance:</p>
<pre><code>- (BOOL)doSomethingWithError: (NSError **)error {

    // other code
    NSError *e;
    if ( ![self bitWithError: &amp;e] ) {
        if (error) *error = e;
        return NO;
    }
    
    return YES;
}
</code></pre>
<p>This seems pretty reasonable, but can get unmanageable quickly:</p>
<pre><code>- (BOOL)doSomethingWithError: (NSError **)error {
    
    NSError *e;
    
    if ( ![self part1WithError: &amp;e] ) {
        if (error) *error = e;
        return NO;
    }
    
    if ( ![self part2WithError: &amp;e] ) {
        if (error) *error = e;
        return NO;
    }
    
    if ( ![self part3WithError: &amp;e] ) {
        if (error) *error = e;
        return NO;
    }
    
    return YES;
}
</code></pre>
<p>Thankfully, blocks can simplify this for us!</p>
<pre><code>- (BOOL)doSomethingWithError: (NSError **)error {

    BOOL(^fail)(NSError *e) = ^(NSError *e) {
        if (error) *error = e;
        return NO;
    };
    
    NSError *e;
    if ( ![self part1WithError: &amp;e] ) return fail(e);
    
    if ( ![self part2WithError: &amp;e] ) return fail(e);
    
    if ( ![self part3WithError: &amp;e] ) return fail(e);
    
    return YES;
}
</code></pre>
<p>Using a fail block has a few advantages:</p>
<ul>
<li>You have a single place through which all errors in this method are routed. You can put a breakpoint here, or add logging.</li>
<li>If you change what doSomethingWithError returns, you change just the return type of the block and the return within the block.</li>
<li>You eliminate a lot of redundant code, therefore lessening the chance of an error in one of the copies.</li>
</ul>
<p>Footnote: Usually, if I am writing an if statement, I’ll write it like this:</p>
<pre><code>if (foo) {
    // statement
}
</code></pre>
<p>I do this even when it’s not necessary, because what if I expand on it later? And I think this is a good principle. But for a fail block like this, I’m <em>never</em> going to add an extra statement. The whole point of the block is to make sure that the failure code is a single statement.</p>]]></content:encoded>
    </item>
    <item>
      <title>Networking using NSURLConnection</title>
      <link>https://tewha.net/2012/06/networking-using-nsurlconnection/</link>
      <pubDate>Mon, 04 Jun 2012 14:00:00 +0000</pubDate>
      <guid>https://tewha.net/2012/06/networking-using-nsurlconnection/</guid>
      <description>&lt;p&gt;In a previous article, I mentioned how to &lt;a href=&#34;handling-302303-redirects&#34;&gt;handle 302/303 redirects to web services&lt;/a&gt;. But that’s a fairly advanced topic, and we should have built up to that.&lt;/p&gt;
&lt;p&gt;What I’m going to cover:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The basics of networking using &lt;code&gt;NSURLConnection&lt;/code&gt;, part of Apple’s Foundation framework.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;What I’m not going to cover:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;How to determine if a connection is available before trying a request. (Hint: Don’t.)&lt;/li&gt;
&lt;li&gt;How to retry an operation when a connection becomes available. (Hint: Reachability.)&lt;/li&gt;
&lt;li&gt;How to abstract this without losing anything important, and bring it all under control. (Hint: Use &lt;a href=&#34;https://github.com/AFNetworking/AFNetworking/&#34;&gt;AFNetworking&lt;/a&gt;.)&lt;/li&gt;
&lt;/ul&gt;</description>
      <content:encoded><![CDATA[<p>In a previous article, I mentioned how to <a href="handling-302303-redirects">handle 302/303 redirects to web services</a>. But that’s a fairly advanced topic, and we should have built up to that.</p>
<p>What I’m going to cover:</p>
<ul>
<li>The basics of networking using <code>NSURLConnection</code>, part of Apple’s Foundation framework.</li>
</ul>
<p>What I’m not going to cover:</p>
<ul>
<li>How to determine if a connection is available before trying a request. (Hint: Don’t.)</li>
<li>How to retry an operation when a connection becomes available. (Hint: Reachability.)</li>
<li>How to abstract this without losing anything important, and bring it all under control. (Hint: Use <a href="https://github.com/AFNetworking/AFNetworking/">AFNetworking</a>.)</li>
</ul>
<p>All of these are topics I’ll write about in future articles. But today, just the basics!</p>
<p>Also, this code will assuming you’re using Automatic Reference Counting. Because <a href="/2012/05/automatic-reference-counting/">you ought to be</a>.</p>
<p>For any HTTP operation, you’re going to use <code>NSURLConnection</code>. It’s not safe to use synchronously from the main thread. This will cause the main thread to stop responding to user-level events, and iOS will quit your application. It behaves exactly as if your application crashed.</p>
<p>On Mac OS X, the system will not quit your application, though your application will become unresponsive and <strong>look</strong> like it’s frozen. So on Mac OS X, you should follow the same pattern of avoiding synchronous network requests on the main thread of your application.</p>
<p>That leaves three options:</p>
<ol>
<li>Asynchronous networking on the main thread.</li>
<li>Synchronous networking on another thread.</li>
<li>Asynchronous networking on another thread.</li>
</ol>
<p>Under normal circumstances, you don’t need to run networking operations on a different thread. There’s very few problems that require moving to another thread.</p>
<p>Using asynchronous operation will cause the networking itself to run in the background. You can consider this a dedicated thread by Apple. Your delegate methods will be called in the correct sequence on the main thread to catch up with networking as iOS determines it is appropriate.</p>
<p>Apple includes an example of how to use <code>NSURLConnection</code> in <a href="https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html">URL Loading System Programming Guide, Using NSURLConnection</a>. It’s a short article, full of simple code examples. You should spend a few minutes to read this.</p>
<p>In a nutshell, here’s the pattern:</p>
<ol>
<li>Keep a <code>NSMutableData</code> for your response data.</li>
<li>Clear the contents <code>NSMutableData</code> instance in <code>connection:didReceiveResponse:</code>. (You may receive multiple <code>connection:didReceiveResponse:</code> events as the request is redirected, but you should only use data from the last one.)</li>
<li>Append the data you receive from didReceiveData to the <code>NSMutableData</code>. Don’t try to process it immediately; you will usually receive multiple <code>connection:didReceiveData:</code> events for a single transfer.</li>
<li>In <code>connectionDidFinishLoading:</code>, your data is complete. Here, you can do something with it.</li>
</ol>
<p>The idea here is that your start (or restart) accumulating data in <code>connection:didReceiveResponse:</code>, append data in your <code>connection:didReceiveData:</code>, and actually do something with the data in <code>connection:connectionDidFinishLoading:</code>.</p>
<p>Processing the data shouldn’t really be done on the main thread, either. You can start another thread, but it’s easier to just <code>dispatch_async</code> to a queue that isn’t running on the main thread.</p>
<p>It is possible to run an <code>NSURLConnection</code> on another thread, of course. That thread will need to be using a run loop to receive the delegate events from networking. But unless there’s some reason you need a separate thread, using asynchronous networking is Apple’s solution to this.</p>
<p>Using <code>NSURLConnection</code> requires a class member to accumulate data as its transferred. That means that if you’re going to have multiple simultaneous transfers, you’ll need something more complicated. Probably a wrapper class to drive <code>NSURLConnection</code>, and keep each response separate. By the time you’ve written this wrapper class, you’ve probably written a naive version of <code>AFHTTPRequestOperation</code>, a part of AFNetworking.</p>
<p>But we’ll get to AFNetworking in a future post.</p>
<p>Assuming you only have a single transfer going on at once, your code should look a bit like this:</p>
<pre><code>- (void)doNetworkThing {

    NSURL *URL = [NSURL URLWithString: @&quot;http://tewha.net/&quot;];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL: URL];
    NSURLConnection *connection = [[NSURLConnection alloc]
                                   initWithURLRequest: request];

    receivedData = [[NSMutableData alloc] init]; // should be a class member
    [connection start];
}

- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response {
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error {
    // do something with error here
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    dispatch_async(someQueue, ^{
        // do something that takes a long time with receivedData here
        dispatch_async( dispatch_get_main_queue(), ^{
            // access the UI here
        });
    });
}
</code></pre>
<p>See also:</p>
<ul>
<li><a href="https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html">URL Loading System Programming Guide, Using NSURLConnection</a></li>
<li><a href="https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html">NSURLConnection Class Reference</a></li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Automatic Reference Counting</title>
      <link>https://tewha.net/2012/05/automatic-reference-counting/</link>
      <pubDate>Thu, 31 May 2012 14:00:00 +0000</pubDate>
      <guid>https://tewha.net/2012/05/automatic-reference-counting/</guid>
      <description>&lt;p&gt;If you’re an application developer: Yes, you should use Automatic Reference Counting (ARC).&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>If you’re an application developer: Yes, you should use Automatic Reference Counting (ARC).</p>
<p>Odds are, the compiler understands Objective-C and Cocoa better than you. I don’t mean this as an insult; it certainly understands it better than me. I think you could safely say it understands the rules better than all but maybe a dozen people worldwide. And it knows tricks to use them to a degree that you and I can’t repeat, even if we understood as well as it does.</p>
<p>The rest is just details, but they’re important:</p>
<ol>
<li>You will write a lot less boring code. Code so boring it’s easy to make mistakes.</li>
<li>As a blended compile time and run time process, it has access to tricks that you don’t.</li>
<li>It will a better a job of writing memory management code than you can, even if you write the theoretical perfect memory management code.</li>
<li>It will reduce “high tide” memory usage (somewhat) without any effort on your part.</li>
</ol>
<p>If you are starting a new application, stop thinking about it and just use it.</p>
<p>If you have an existing application, you need to think about it. You’re balancing the ease of future development vs. a need to re-test the app. The ARC conversion isn’t awful, but it isn’t painless or foolproof either. You will need to make sure you have no circular references, and you will need to make sure that objects don’t disappear sooner than you think.</p>
<p>If you have an existing application that targets iOS before iOS 5, zeroing weak references are not supported. You can find people who will tell you that zeroing weak references aren’t a big deal. They’re wrong. While it’s true you can use assign to prevent circular references, weak references are what turns ARC from a useful way to write less code to a fantastic way to write stable applications. You should seriously consider requiring iOS 5.</p>
<p>If you have an existing application that targets iOS before iOS 4, you can’t use it at all. What are you thinking, supporting a version of iOS that old?</p>
<p>See also:</p>
<ul>
<li><a href="https://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226">Transitioning to ARC</a>: Apple’s ARC overview. A great overview, but possibly less than you need to know.</li>
<li><a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html">Automatic Reference Counting</a>: The living and detailed ARC specification and rationales. Certainly much more information than you require.</li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Handling 302/303 redirects</title>
      <link>https://tewha.net/2012/05/handling-302303-redirects/</link>
      <pubDate>Wed, 30 May 2012 14:00:00 +0000</pubDate>
      <guid>https://tewha.net/2012/05/handling-302303-redirects/</guid>
      <description>&lt;p&gt;If you try to POST to a web API using &lt;code&gt;NSURLConnection&lt;/code&gt; that redirects you using a &lt;a href=&#34;http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3&#34;&gt;302&lt;/a&gt; or &lt;a href=&#34;http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4&#34;&gt;303&lt;/a&gt; redirect, you’ll fall over to a GET request. This is intentional, but you can override it.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>If you try to POST to a web API using <code>NSURLConnection</code> that redirects you using a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3">302</a> or <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4">303</a> redirect, you’ll fall over to a GET request. This is intentional, but you can override it.</p>
<p>With HTTP status codes 302 and 303, the user agent (in this case, <code>NSURLConnection</code>) will change the request type from POST to GET. This is just how 302 was usually implemented; status code 303 was added to HTTP/1.1 to make this behaviour explicit.</p>
<p>HTTP/1.1 also added a status code to redirect without changing the request type from POST to GET. If you can change the web site, getting it to redirect you with a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8">307</a> instead will fix the problem.</p>
<p>If not, you can make <code>NSURLRequest</code> ignore this aspect of RFC2616.</p>
<p><code>NSURLRequest</code> sends an event to its delegate, in which you can see what <code>NSURLRequest</code> plans to do and customize it:</p>
<pre><code>- (NSURLRequest *)connection: (NSURLConnection *)connection
             willSendRequest: (NSURLRequest *)request
            redirectResponse: (NSURLResponse *)redirectResponse;
{
    if (redirectResponse) {
        NSMutableURLRequest *r = [[originalRequest mutableCopy] autorelease];
        [r setURL: [request URL]];
        return r;
    } else {
        return request;
    }
}
</code></pre>
<p>By doing this, you’re cloning the original request and changing the URL to match the request suggested by <code>NSURLConnection</code> (which is following the RFC).</p>
<p>See also:</p>
<ul>
<li>w3.org: <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">RFC2616 HTTP/1.1, section 10: Status Code Definitions</a></li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Objective-C memory management</title>
      <link>https://tewha.net/2011/08/objective-c-memory-management/</link>
      <pubDate>Sun, 21 Aug 2011 14:00:00 +0000</pubDate>
      <guid>https://tewha.net/2011/08/objective-c-memory-management/</guid>
      <description>&lt;p&gt;With Automatic Reference Counting (ARC) coming out soon, you could argue this post is coming almost too late. But there’s a lot of confusion over this, and I don’t think ARC will help much if you don’t understand the &lt;em&gt;why&lt;/em&gt; of memory management.&lt;/p&gt;
&lt;p&gt;After a couple years, I’ve come to adopt some very simple rules for memory management.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>With Automatic Reference Counting (ARC) coming out soon, you could argue this post is coming almost too late. But there’s a lot of confusion over this, and I don’t think ARC will help much if you don’t understand the <em>why</em> of memory management.</p>
<p>After a couple years, I’ve come to adopt some very simple rules for memory management.</p>
<h2 id="concepts">Concepts</h2>
<p>The first step is to pick up a few concepts that will help you as you code.</p>
<ul>
<li><strong>Be lazy in memory management.</strong> Rely on the compiler to do everything it possibly can. The compiler can synthesize property setters that handle memory management according to the rules you set. Rely on this.</li>
<li><strong>Ownership.</strong> Think in terms of ownership, rather than reference counting. Thinking in terms of ownership makes problems and solutions obvious. Thinking in terms of ownership will help you keep in mind the <em>why</em> of what you’re doing, rather than the <em>what</em>. After you’ve got a good grasp of <em>why</em>, the <em>what</em> becomes obvious.</li>
<li><strong>Protect your objects.</strong> Own any object that you want to keep around as long as <code>self</code> is around.</li>
<li><strong>Avoid circular references.</strong> Never own an object that could own <code>self</code>. This means never owning <code>self</code>’s delegate or data source.</li>
</ul>
<h2 id="practical_guidelines">Practical guidelines</h2>
<p>But how does this translate to code? There’s a few specific and concrete things you can do to make this easier on yourself:</p>
<ul>
<li><strong>Use properties to centralize memory management rules.</strong> Use <code>@property</code> to establish the rules for memory management of an instance variable. (And <code>@synthesize</code> your properties to underscored instance variables to prevent naming conflicts.)</li>
<li><strong>Pick the right memory management rule.</strong> Use <code>retain</code> properties as your default. Data sources, delegates or other objects that might own the object you’re working in should be <code>assign</code> properties instead of <code>retain</code>.</li>
<li><strong>Rely on the centralized memory management rules.</strong> Use property set notation (<code>self.foo = nil;</code>) or the property setter (<code>[self setFoo: nil];</code>) everywhere you change the property’s value except in the property’s setter (if you need one) In this way, you rely on the <code>retain</code> or <code>assign</code> in your <code>@property</code> to specify the memory management. If you need to use <code>retain</code>, <code>release</code> or <code>autorelease</code> outside of a setter you’re doing too much. (And, also, you’ll have more work to do to be compatible with ARC.)</li>
<li><strong>Avoid being called once deallocated.</strong> In <code>dealloc</code>, <code>nil</code> any delegates you’ve set to <code>self</code>. (This eliminates the possibility that the object will survive longer than <code>self</code> and try to send messages to <code>self</code>.)</li>
<li><strong>Protect your private bits, too.</strong> Don’t use raw instance variables in objects requiring memory management. Use anonymous properties.</li>
<li><strong>Containers own their contents.</strong> You not only don’t need to but must not try to manage memory in a system container. An <code>NSArray</code> will send a <code>retain</code> to objects that are added to it, and a <code>release</code> to objects as they are removed. If you try to manually <code>retain</code> and <code>release</code> objects, you’ll miss a case.</li>
<li><strong>Verify.</strong> Analyze your code frequently. And profile your code early and often for leaks.</li>
</ul>]]></content:encoded>
    </item>
  </channel>
</rss>
