<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>MKBlog &#187; Articles</title>
	<atom:link href="http://blog.mugunthkumar.com/category/articles/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.mugunthkumar.com</link>
	<description>iPhone, iPad, Windows Phone Development and Usability Guidelines</description>
	<lastBuildDate>Mon, 30 Jan 2012 02:54:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Migrating your code to Objective-C ARC</title>
		<link>http://blog.mugunthkumar.com/articles/migrating-your-code-to-objective-c-arc/</link>
		<comments>http://blog.mugunthkumar.com/articles/migrating-your-code-to-objective-c-arc/#comments</comments>
		<pubDate>Fri, 23 Dec 2011 23:00:08 +0000</pubDate>
		<dc:creator>Mugunth Kumar</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Featured Articles]]></category>
		<category><![CDATA[arc]]></category>
		<category><![CDATA[ios 4]]></category>
		<category><![CDATA[ios5]]></category>
		<category><![CDATA[lion]]></category>
		<category><![CDATA[objective c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[snow leopard]]></category>

		<guid isPermaLink="false">http://blog.mugunthkumar.com/?p=1412</guid>
		<description><![CDATA[Recently, Apple introduced several new developer stuff including Xcode 4, ARC, LLVM Compiler 3.0 and iOS 5. From some of the questions on Stack overflow, I could understand that, most of the ARC related confusions arise due to the fact that, developers don&#8217;t know if &#8220;ABC&#8221; is a feature/restriction of LLVM 3.0 or iOS 5 [...]
Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/' rel='bookmark' title='MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions'>MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions</a> <small>MKStoreKit started off in a pet project a couple of...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>Recently, Apple introduced several new developer stuff including Xcode 4, ARC, LLVM Compiler 3.0 and iOS 5. From some of the questions on Stack overflow, I could understand that, most of the ARC related confusions arise due to the fact that, developers don&#8217;t know if &#8220;ABC&#8221; is a feature/restriction of LLVM 3.0 or iOS 5 or ARC.</p>
<p>Retain cycles, auto-release pools, @autorelease blocks, oh man! So many new things? What am I going to do? You are right. ARC, or Objective-C Automatic Reference Counting is almost <a href="http://blog.mugunthkumar.com/articles/random-thoughts-on-ipad/">as magical as the iPad</a>. No really!</p>
<p>In this post, I&#8217;ve made an attempt to demystify the air around this. Before starting, I&#8217;ll have to warn you that, this is a fairly long post. If you are too bored, Instapaper this article and read it later. But, hopefully, at the end of this, I believe, you will have a better understanding on how ARC works and be able to work around the innumerable errors it spits out when you convert your project.</p>
<p>Having said that, let&#8217;s get started.</p>
<h2>What is ARC</h2>
<p>ARC is a feature of the new LLVM 3.0 compiler that helps you to write code without worrying <strong><em>much</em></strong> about memory management. Memory management can be broadly classified into two, garbage collected and reference counted models. Before going to the details, let’s briefly discuss these two models and understand why ARC is even needed.</p>
<h4>Problems with the current model.</h4>
<p>The current memory model we use in Objective-C is manual reference counting on iOS and Garbage collection on Mac.</p>
<p>There are certain problems with both these memory models which probably was the reason why ARC was developed.</p>
<h5>Garbage collection</h5>
<p>Garbage collection is a higher level language feature probably introduced in Java (or technically, Java Virtual Machine) and implemented in a variety of other programming platforms including Microsoft’s Common Language Runtime. While Garbage collection worked well for higher level languages, Objective-C, which is still C under the hood, didn’t really fly high. Pointers (or rather references) in other languages like Java were actually objects that managed retain count and automatically releases itself when the count reaches zero. One of the design goals of C was to be optimized for performance and not “easy of use”. While pointer objects (read <a href="http://en.wikipedia.org/wiki/Smart_pointer">smart pointers</a>) are great object oriented abstractions, they have an adverse effect on the performance of the code and since Objective-C was intended primarily for native programming where developers are used to use pointers, pointers within a structure, pointer to a pointer (for dereferencing a out parameter), it was just too difficult to introduce something like a smart pointer that would require a lot of mindset change from the developers who prefer a deterministic memory management model (Reference counting) over a non-deterministic memory management model (Garbage collection). Nevertheless, GC (<a href="http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)#Generational_GC_.28ephemeral_GC.29">Generational GC</a>) was introduced in Objective-C 2.0 for Mac. While Generational GC doesn&#8217;t suffer from &#8220;Stop the world&#8221; issues like the mark and sweep alogrithm, they don&#8217;t collect every released variable and an occasional mark and sweep collection is still needed.</p>
<h5>Reference Counting</h5>
<p>The memory management model used in iOS is called as reference counting model, or more precisely, manual reference counting.<br />
In manual reference counting model, you as a developer, have to deallocate every object you allocated. When you don’t do this, you either leak memory or over release it, causing a crash. While that counting sounds easy, Most of the memory leaks happen when you transfer ownership of objects across scope boundaries. That’s a creator method that allocates an object for you and expects the caller to deallocate it. To circumvent this problem, Objective-C introduced a concept called autorelease. auto-released variables are added to the auto-release pool and are released at the end of the runloop. While this sounds too good, auto-release pools do incur an additional overhead.</p>
<p>For example, comparing the two code blocks,</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>dict <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDictionary</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #11740a; font-style: italic;">// do something with the dictionary here</span>
    <span style="color: #11740a; font-style: italic;">// I'm done with the dictionary, I don't need it anymore</span>
    <span style="color: #002200;">&#91;</span>dict release<span style="color: #002200;">&#93;</span>;
    <span style="color: #11740a; font-style: italic;">// more code</span>
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>and</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>dict <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDictionary</span> dictionary<span style="color: #002200;">&#93;</span>; <span style="color: #11740a; font-style: italic;">// auto-released object</span>
    <span style="color: #11740a; font-style: italic;">// do something with the dictionary here</span>
    <span style="color: #11740a; font-style: italic;">// I'm done with the dictionary, I don't need it anymore</span>
&nbsp;
    <span style="color: #11740a; font-style: italic;">// more code</span>
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>the first block is an example of optimized use of memory where as the second depends on auto-release pools. While this block of code doesn’t really incur significant memory overhead, code like these slowly adds together and makes your reference counted model heavily dependent on auto-release pools. That is, objects that you know could be deallocated, will still linger around in the auto-release pool for a little longer.</p>
<h5>Automatic Reference Counting</h5>
<p>Say hello to ARC. ARC is a compiler feature that auto inserts retain and release for you. So in the first code block of the above example, you no longer have to write the release method and ARC auto-inserts for you before compilation.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>dict <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDictionary</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #11740a; font-style: italic;">// do something with the dictionary here</span>
    <span style="color: #11740a; font-style: italic;">// I'm done with the dictionary, I don't need it anymore</span>
    <span style="color: #002200;">&#91;</span>dict release<span style="color: #002200;">&#93;</span>; <span style="color: #11740a; font-style: italic;">// ARC inserted</span>
    <span style="color: #11740a; font-style: italic;">// more code</span>
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>When you create an autoreleased object, like in the second block of code, ARC compiler is clever enough not to add a release call. Sound great, so how should I go about doing this ARC thing? Just delete all release/retain codes and pray? Unfortunately, it isn&#8217;t that easy. ARC is not just some auto insert or macro expander kind of tool. <strong>It forces you to think in terms of object graphs instead of memory allocation, retain or release.</strong> Let&#8217;s delve a little deeper into ARC.</p>
<h3>Compiler level feature</h3>
<p>ARC is a compiler level feature. I repeat. ARC IS A COMPILER LEVEL FEATURE. This means, when you use ARC, you don’t have to worry about upgrading your deployment target and so on. However, only the latest LLVM 3.0 compiler supports ARC. If you are still stuck with GCC, you are out of luck. (Meh!) Some more points that you should know about ARC are,</p>
<ul>
<li>ARC is backward compatible with libraries and framework compiled with under non-ARC.</li>
<li>ARC can be used within your project on a file-by-file basis. So you can mix and match ARC code with non-ARC code.</li>
<li>You can also integrate ARC compiled libraries into your project that doesn’t use ARC and vice-versa.</li>
<li>You use a <strong>compiler switch</strong> to turn ARC on and off.</li>
<li>(The keyword here is compiler switch)</li>
<li>You can also set the complete target to build with ARC by default (and use non-ARC compiler only when instructed so.) This is shown in the illustration below.</li>
<li><img title="ARC - Xcode.png" src="http://blog.mugunthkumar.com/wp-content/uploads/ARC-Xcode.png" alt="ARC  Xcode" width="600" height="229" border="0" /></li>
</ul>
<p>The two main compiler switches that you would often use are when you build your application with a third party library that is not ARC compliant and vice versa, are</p>
<ul>
<li>-f<strong>no-objc-arc</strong></li>
<li>-f<strong>objc-arc</strong></li>
</ul>
<p>-f is the switch and <strong>no-objc-arc</strong> and <strong>objc-arc</strong> are the options that you are turning on. As evident from the names, the first one turns off ARC and the second turns on.</p>
<p>For example, if your application is ARC enabled but a third party library is not, you use the first switch <strong>-fno-objc-arc</strong> to exclude the third party library. Conversely, if your application is not yet ARC enabled (gasp!) but the third party library you are integrating is, you use the second switch <strong>-fobjc-arc</strong> You add these flags to the project from the Build phases tab as shown below.<img title="Xcode-2-1.png" src="http://blog.mugunthkumar.com/wp-content/uploads/Xcode-2-1.png" alt="Xcode 2 1" width="600" height="374" border="0" /></p>
<h3>Also a run time feature</h3>
<p>Wait! You just told me (and repeated) that ARC is a compiler level feature? Now what? Sorry, I hear you, but, unfortunately, things aren&#8217;t that easy and it doesn&#8217;t just stop here. ARC also backs up on a runtime feature called <em>zero-ing weak references</em>. Oh, damn, another keyword! I should have introduced this before. But that’s ok. We will revisit about the run-time dependency of ARC, a little later in this post.</p>
<h4>ARC Ownership qualifiers</h4>
<p>As I showed you earlier, ARC automatically inserts releases and retains in your code in a pre-compilation step. But for ARC to know when to release your objects and when to retain them, you need to somehow tell the life of your variables. You use ownership qualifiers for that. A strong understanding of ownerships is vital to understand and use ARC properly. Once you understand this concept, you will be thinking in terms of object graphs instead of retain/release. Secondly, when you use ARC, all variables local or ivars are initialized to nil automatically for you. This means, there is little chance of having a dangling reference in your application.</p>
<ul>
<li>__strong</li>
<li>__weak</li>
<li>__unsafe_unretained</li>
<li>__autoreleasing</li>
</ul>
<p>The first qualifier, __strong, is the default and you might not even be using this explicitly. It is use to tell the ARC compiler that, the declared variable &#8220;owns&#8221; the reference. The opposite of this is __weak, which tells the ARC compiler that the declared variable doesn&#8217;t own the reference.</p>
<p>The __weak is <em>synonymous</em> to the &#8220;assign&#8221; modifier. You normally use assign modifier for IBOutlets and delegates. Under ARC, this is replaced with __weak. However, there is a caveat. __weak requires you to deploy the app on a runtime that supports <em>zero-ing weak references</em>. This includes, iOS 5 and Lion. Snow Leopard and older operating systems or iOS 4 and older operating systems don&#8217;t support zero-ing weak references. This obviously means you cannot use __weak ownership modifiers if you plan to deploy to older operating systems. Fret not. ARC includes another ownership qualifier, __unsafe_unretained that is synonymous to __weak, except that when the pointer is de-referenced, it is not set to nil, but remains dangling. A while ago, I told something about zero-ing weak references? When the runtime supports zero-ing weak references, your __weak variables are automatically set to nil when they are released. This is the only feature that requires a higher deployment target (iOS 5/Lion). Otherwise, you are good to deploy on iOS 4/Snow Leopard.</p>
<p>A couple other important things to know about __weak vs __unsafe_unretained is that, the compiler doesn&#8217;t allow you to use __weak when your deployment target is set to a operating system that doesn&#8217;t support zero-ing weak references. The Convert to Objective-C ARC wizard uses __weak only when your deployment target supports zero-ing weak references. So if your deployment target is iOS 4, the Objective-C convert ion wizard will replace assign modifiers with __unsafe_unretained instead of __weak.</p>
<p>The last ownership qualifier, __auto_releasing is used mostly when passing a reference to a function for writing out. You would use this in places where you normally use pointer indirection like returning a NSError object via an out parameter.</p>
<p>Properties in your header file can also have the above ownership qualifiers except the __auto_releasing. When applied to properties, ARC automatically generates the correct code in dealloc to release them when the object dies.</p>
<p>Lastly, and more importantly, all of ARC managed <strong>objects</strong> are initialized to nil when they are created. So, again, no more dangling pointers because you forgot a initialize statement. However, do note that this initialization doesn&#8217;t initialize primitive data types. So a declaration like,</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">int</span> a;</pre></div></div>

<p>might contain a garbage value for a.</p>
<p>Whew! That&#8217;s pretty taxing. Take a break. We just started.</p>
<h3>ARC knows more Objective-C than you</h3>
<p>ARC also taps into a the Objective-C language naming conventions and infers the ownership of the returned object.</p>
<p>In Objective-C, a method that stats with any one of the following prefix,</p>
<ul>
<li>init,</li>
<li>alloc,</li>
<li>copy,</li>
<li>mutableCopy and</li>
<li>new</li>
</ul>
<p>are considered to be transferring ownership of the returned object to the caller.<br />
This means, in your application, when you create a method, ARC automatically infers whether to return a autoreleased object or a +1 retained object from your method name. In fact, in most cases, instead of returning auto-release objects, ARC just inserts a manual release in the calling code, automatically for you. However, there is a small caveat. Let&#8217;s assume that you have a method that starts with &#8220;copy&#8221;, as in</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> copyRightString;</pre></div></div>

<p>ARC assumes that it would transfer the ownership of the returned string to the caller and inserts a release automatically. Everything works well, if both the called method and the calling method are compiled using ARC.</p>
<p><strong><em>But</em></strong> if your &#8220;copyRightString&#8221; method is in a third party library that isn&#8217;t compiled with ARC, you will over-release the returned string. This is because, on the calling code, ARC compiler inserts a release to balance out the retain count bumped up by the &#8220;copy&#8221; method. Conversely, if the third party library is compiled with ARC and your method isn&#8217;t, you will have a memory leak. You can however override this behavior by adding one of the following attribute to your methods.</p>
<ul>
<li>NS_RETURNS_NON_RETAINED</li>
<li>NS_RETURNS_RETAINED</li>
</ul>
<p>So your method will now look like this.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> copyRightString NS_RETURNS_NON_RETAINED;</pre></div></div>

<p>You can also rename the method name to <strong>copyrightString</strong> (note the case) or <strong>getCopyRightString</strong> instead of adding an attribute. However, I wouldn&#8217;t recommend the former method as it breaks the cocoa naming conventions (prefixing a method with &#8220;get&#8221; or &#8220;set&#8221; is Java-ish)</p>
<p>You will see methods having the NS_RETURNS_* prefixes throughout the header files in Apple&#8217;s own UIKit.framework or the foundation classes. Now that you know what happens behind the scenes and how compiler treats these decorations, you can solve crazy memory issues, like a crash when you call a <strong>copyRightString</strong> in your method in a third party library.</p>
<p>With that, let&#8217;s get ready for climbing the next peak.</p>
<h3>Toll-free bridging</h3>
<p>ARC <strong>doesn’t</strong> manage Core Foundation objects. They say, there is no free lunch. ARC, takes it one step further. There is no free-casting between Core Foundation objects and equivalent Objective-C objects (NS* objects). Yes, that&#8217;s right. You cannot cast a Core Foundation object to an equivalent Objective-C object (NS* object) without telling ARC how to manage ownerships.</p>
<p>Let&#8217;s now see how to specify ownership transfers when you cast a Core Foundation object.<br />
The following ownership transfer modifiers should be provided when you cast a Objective-C object to a Core Foundation object.</p>
<ul>
<li>__bridge</li>
<li>__bridge_retained</li>
<li>__bridge_transfer</li>
</ul>
<p>When you migrate a project to ARC, you would have seen error messages like the one below.</p>
<div class="wp-caption aligncenter" style="width: 572px"><img style="border-style: initial; border-color: initial; border-width: 0px;" title="Toll-free bridging.png" src="http://blog.mugunthkumar.com/wp-content/uploads/Toll-free-bridging.png" alt="Toll free bridging" width="562" height="196" border="0" /><p class="wp-caption-text">ARC Error because of a missing bridge attribute in a Toll-free bridging code</p></div>
<p>You might also have proceeded by accepting the suggestions provided by the LLVM compiler. But now, let&#8217;s dig deeper and understand the &#8220;why&#8221; behind it.</p>
<p>The modifier, __bridge tells the ARC compiler that, it&#8217;s a plain simple, bridging cast. That means, you ask the ARC compiler to do nothing extra when the transfer is made. You might think, if that is the case, Apple could have made this the default choice. But it was not made probably because, it&#8217;s to preposterous to make such an assumption. Making such a bold assumption means, you would easily leak memory as there isn&#8217;t a easier way to tell when you are actually releasing a Core Foundation object unlike a Objective-C object.</p>
<p>The second modifier, __bridge_retained is used to tell the ARC compiler that the Objective-C object should be transferred to Core Foundation by bumping the retain count by 1 and it should be treated as if it is a newly created object (as opposed to a auto-released object). You use this modifier if the method was probably named like a creation method (starting with init, copy, mutableCopy etc.,) or if you are going to release the Objective-C object inside of Core Foundation using methods like CFRelease.</p>
<p>The last modifier, __bridge_transfer is used to tell the ARC compiler that the Core Foundation object is to be transferred to ARC with a retain count of 1. This is used if you created a Core Foundation object using one of the CF***Create methods and want the ARC compiler to handle the memory management for you. That&#8217;s you are transferring a Core Foundation object to ARC with a retain count of 1.</p>
<p>As a side note on this, avoid using __bridge_retained and __bridge_transfer to trick the compiler to add retain and releases for you. Use it to improve your code readability and minimizing the number of manual memory management calls. (Move on if you don&#8217;t understand this line. You will start understanding this automatically when you start using this in your own code)</p>
<h2>How does ARC work internally?</h2>
<p>ARC ain&#8217;t magic, if you know how it works. But a little knowledge is a dangerous thing. Knowing how the ARC compiler works will help you more in understanding the error messages and compiler warnings spat out by it.</p>
<p>The ARC compiler has two main parts, a front end compiler and an optimizer.</p>
<h3>ARC front end</h3>
<p>The ARC front end compiler checks for every &#8220;owned&#8221; Objective-C object and inserts release appropriately. By owned object, I mean, an object whose ownership qualifier has been set. For example, if the &#8220;owned&#8221; object is a local variable, ARC front end compiler inserts a release at the end of the scope. This is because, by default all local variables are &#8220;strong&#8221; ly owned. If the object is a instance variable, the ARC front end compiler inserts a release statement in the dealloc method, if the ownership type is strong. For unsafe_unretained or weak ownership ARC doesn&#8217;t do anything. It also takes care of calling the [super dealloc] for you and intact ARC compiler doesn&#8217;t allow you to explicitly call dealloc.</p>
<p>The ARC front end compiler also takes care of generating errors when it encounters a variable (local or instance) whose ownership qualifier is not set or when you explicitly calling dealloc.</p>
<h3>ARC optimizer</h3>
<p>The function of the ARC optimizer is to optimize the retain and release statements by removing them if they are inserted multiple times by the ARC front end compiler. It is this optimizer that ensures that performance is not affected by calling retain and release multiple times.</p>
<h2>The actual Migration using Xcode 4.2</h2>
<p>Xcode 4.2 has a wizard to automatically migrate your code for use with the ARC compiler. This means, the wizard rewrites some of your code, removes calls to retain/release and removes dealloc methods and calls to [super dealloc] for you.</p>
<p>The first step is to open your project, select Edit -&gt; Refactor -&gt; Convert to Objective-C ARC from the menu.</p>
<div class="wp-caption alignnone" style="width: 610px"><img style="border-style: initial; border-color: initial; border-width: 0px;" title="Refactor option.png" src="http://blog.mugunthkumar.com/wp-content/uploads/Refactor-option2.png" alt="Refactor option" width="600" height="417" border="0" /><p class="wp-caption-text">Migrating to Objective-C ARC using Xcode 4.2</p></div>
<p>When you select this option, you will be asked to select a target. If you have only one target, it&#8217;s fine. If you have multiple targets in your application, you have to perform the ARC migration on every target. After you select a target, the wizard by default selects all source code files that belong to that project for ARC migration. If you are using third party libraries that are not yet ARC ready, you can uncheck those files in this step. This is illustrated in the screenshot below.</p>
<div class="wp-caption alignnone" style="width: 610px"><img style="border-style: initial; border-color: initial; border-width: 0px;" title="Uncheck.png" src="http://blog.mugunthkumar.com/wp-content/uploads/Uncheck1.png" alt="Cannot convert" width="600" height="403" border="0" /><p class="wp-caption-text">Selecting your files for ARC exclusion</p></div>
<p>In the above project, since I know that ASIHttpRequest is not yet ARC compatible, I&#8217;m selecting them and command-clicking them to show the option to uncheck all of them. When you do this, the wizard automatically adds a -fno-objc-arc compiler flag for all these files.</p>
<p>The next step is to start the pre-checking process. The pre-checking process compiles the project and analyzes for potential problems before performing the actual migration. You might almost and always get a error message like this.</p>
<div class="wp-caption alignnone" style="width: 444px"><img style="border-style: initial; border-color: initial; border-width: 0px;" title="Cannot convert.png" src="http://blog.mugunthkumar.com/wp-content/uploads/Cannot-convert1.png" alt="Cannot convert" width="434" height="148" border="0" /><p class="wp-caption-text">The dreaded error message!</p></div>
<p>Of course, 58 errors in this screenshot is actually quite low. You should expect anywhere in the range of 300+ for a mid sized project. But fret not, they aren&#8217;t complicated at all to fix.</p>
<h2>Common ARC migration errors</h2>
<p>The number of errors that might prevent you from converting your project to ARC is usually high if your code is &#8220;old&#8221; or if it doesn&#8217;t adhere to Objective-C design patterns. For example, accessing a iVar. While it&#8217;s technically ok, you should almost and always use properties to access them outside of init and dealloc methods. If you have been using properties, ARC migration would be painless. If you were old skool, you have to feel the pain now. In this last section, I&#8217;ll show you the most commonly occurring errors when you migrate your project.</p>
<h3>Cast of Objective-C pointer to C Pointer type</h3>
<p>This error is generated because ARC doesn&#8217;t do toll-free bridging for you. As I explained before in the section, Toll-free bridging, requires the developer to explicitly specify ownership transfer qualifiers.<br />
Use the various ownership transfer qualifiers I showed you before to fix this problem.</p>
<h3>performSelector may cause a leak because its selector is unknown</h3>
<p>We now know that Objective-C ARC compiler knows more Objective-C than you. This error message is because of that. The ARC compiler tries to identify the method family and determine whether to add a retain or release to the returned value from the caller code. This means, if your method starts with init, alloc, copy, mutableCopy or new, the ARC compiler will add a release to the calling code after the variable scope ends. Since are using a selector to call a method dynamically at runtime, ARC doesn&#8217;t really know if the method called returns a +1 retained object or a auto-released object. As such, ARC cannot reliably insert a retain or release to the returned object after its scope ends. This warning is shown to warn you of potential memory leaks.</p>
<p>If you are sure that your code works fine without memory leaks, you can ignore this warning. To suppress this warning, you can turn off the compiler flag -Warc-performSelector-leaks warning on a line by line basis like this.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#pragma clang diagnostic push</span>
<span style="color: #6e371a;">#pragma clang diagnostic ignored &quot;-Warc-performSelector-leaks&quot;</span>
    <span style="color: #002200;">&#91;</span>self performSelector<span style="color: #002200;">:</span>self.mySel<span style="color: #002200;">&#93;</span>;
 <span style="color: #6e371a;">#pragma clang diagnostic pop</span></pre></div></div>

<p>Unfortunately, you cannot annotate a dynamic selector using __attribute__ ((objc_method_family(*))).</p>
<h3>Receiver type &#8220;*&#8221; doesn&#8217;t declare the method with selector &#8220;*&#8221;</h3>
<p>ARC mandates that every method you call should be declared properly. With GCC, this was a warning. But LLVM makes this step mandatory since ARC needs to accurately identify and that is why you see an error like this.</p>
<div class="wp-caption alignnone" style="width: 610px"><img style="border-style: initial; border-color: initial; border-width: 0px;" title="Undeclared Selectors.png" src="http://blog.mugunthkumar.com/wp-content/uploads/Undeclared-Selectors1.png" alt="Undeclared Selectors" width="600" height="28" border="0" /><p class="wp-caption-text">Error that you see when you don&#39;t declare a receiver type</p></div>
<p>This error is also because of the fact that ARC needs to identify the method family to determine if it has to add a retain or release to the returned object. For example, in the above code, the method, returnMyGreatObject might return a NS_RETURNS_RETAINED. In this case, the ARC compiler has to insert a release after the returned object goes out of scope. The ARC compiler can know this only when you declare it formally. This is why, under ARC method declarations are mandatory. If you have been declaring methods formally under GCC, even when the compiler didn&#8217;t enforce (so that the code was aesthetically beautiful) you wouldn&#8217;t see this error at all. As I said before, the number of ARC migration errors is directly proportional to the quality of code you write. Fixing this error is fairly simple and all you have to do is to declare every method formally in the header file or on a private category extension.</p>
<h3>Common workarounds that you use in ARC on code that otherwise looks normal</h3>
<p>In some cases, while using ARC, you might end up writing code that looks as if it&#8217;s written to &#8220;please&#8221; the ARC compiler rather than writing natural code. Unfortunately, nothing can be done to this and we all have to live with this. The next two sections explain when you might need to write unnecessary code like this to please the compiler.</p>
<h4>Capturing &#8220;*&#8221; strongly is likely to lead to a retain cycle</h4>
<div class="wp-caption alignnone" style="width: 610px"><img style="border-style: initial; border-color: initial; border-width: 0px;" title="Capture.png" src="http://blog.mugunthkumar.com/wp-content/uploads/Capture1.png" alt="Capture" width="600" height="69" border="0" /><p class="wp-caption-text">ARC and retain cycles</p></div>
<p>The last category of warning message is shown when a retain cycle is detected in your code. An example is shown below.</p>
<p>This code was probably leaking the request object before ARC and increasing your memory footprint. But, thanks to ARC. You now know that code like these cause retain cycles that cannot be released automatically. Circumventing a retain cycle issue almost and always ends up breaking the cycle with a weak reference.</p>
<p>Fixing this error is fairly simple and in this case, you can get a weak reference to the request object and copy it to the block. Within the block, convert it again to a strong reference. This is illustrated below.</p>
<div class="wp-caption alignnone" style="width: 580px"><img style="border-style: initial; border-color: initial; border-width: 0px;" title="Capture fixed.png" src="http://blog.mugunthkumar.com/wp-content/uploads/Capture-fixed1.png" alt="Capture fixed" width="570" height="118" border="0" /><p class="wp-caption-text">Workaround for ARC and retain cycle issue</p></div>
<p>In the above code block, you can also replace references to __unsafe_unretained with __weak if you are deploying to a runtime that supports zero-ing weak references.</p>
<h4>Avoiding retain cycles using __block</h4>
<p>Sometimes, you need an object to live till as long as the completion handler on it can live. For example, a Block based UIAlertView can call a completion handler after the user presses a button on the UIAlertView.<br />
For example,</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">UIAlertView <span style="color: #002200;">*</span>alertView <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIAlertView alertViewWithTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Test&quot;</span> buttons<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithObjects<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Ok&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cancel&quot;</span>, <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span> completionHandler<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> tappedButtonIndex<span style="color: #002200;">&#41;</span>  <span style="color: #002200;">&#123;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// do something based on the button tapped on alertView</span>
<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>alertView show<span style="color: #002200;">&#93;</span>;</pre></div></div>

<p>In the above case, the alertView gets deallocated by ARC as soon as it&#8217;s shown and the call to completionHandler never gets executed (or even crashes).<br />
To prevent this, you can use the __block decoration on UIAlertView declaration and copy it inside the block like</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">__block UIAlertView <span style="color: #002200;">*</span>alertView <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIAlertView alertViewWithTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Test&quot;</span> buttons<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithObjects<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Ok&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cancel&quot;</span>, <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span> completionHandler<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> tappedButtonIndex<span style="color: #002200;">&#41;</span>  <span style="color: #002200;">&#123;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// do something based on the button tapped on alertView</span>
	alertView <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>alertView show<span style="color: #002200;">&#93;</span>;</pre></div></div>

<p>ARC takes care of releasing it when you nil it inside the completionHandler. You will find this pattern used a lot when you work with completionHandlers in TwTweetComposeViewController or even UIViewController presentViewController:animated:completion: methods.</p>
<h2>That last question</h2>
<h3>When should you migrate?</h3>
<p><strong>NOW</strong></p>
<p>The performance benefits you get by using ARC is remarkable. Apple claims that the @autoreleasepool is over 6 times faster than NSAutoReleasePool objects used in your non-ARC code. This is because, @autoreleasepools don&#8217;t allocate objects and all it does is must bump up the pointer retain counts. Similarly, NSObjects&#8217; retain and release are optimized that you can expect a performance boost of anywhere around 2.5x. The third important performance benefit you will see is in methods that return autoreleased object. Under ARC, this variable is no longer transferred using the auto-release pool and what instead happens is a ownership transfer. Again this is upto 20x faster.</p>
<p>Hence, don&#8217;t wait till your dependent third party frameworks are migrated to ARC. You can always exclude them and go ahead and convert your code to ARC now.</p>
<h2>Where to go from here?</h2>
<ul>
<li>WWDC 2011 – Session 322 Introduction to Automatic Reference Counting</li>
<li>WWDC 2011 – Session 322 Objective-C Advancements in depth</li>
<li>Stop: You are warned. This link is only for hard code geeks. <a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html">http://clang.llvm.org/docs/AutomaticReferenceCounting.html</a></li>
<li>WWDC 2011 – Session 308 &#8211; Blocks and Grand Central Dispatch in Practice</li>
</ul>
<p>One last word, treat this post as a living document. I&#8217;ll be updating the last few sections on new workarounds as and when I find a fix for them.</p>
<p>&#8211;<br />
Mugunth</p>
<p><map name='google_ad_map_1412_8b86e81420c6776e'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/1412?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_1412_8b86e81420c6776e' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=1412&amp;url= http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fmigrating-your-code-to-objective-c-arc%2F' /></p><p><a href ="http://twitter.com/mugunthkumar">Follow me </a> on Twitter</p><p>&copy;2012 <a href="http://blog.mugunthkumar.com">MKBlog</a>. All Rights Reserved.</p>.<h4 id="tweetandlike-heading"></h4><ul id="tweetandlike-buttons"><li><a href="http://twitter.com/share" data-title="Migrating+your+code+to+Objective-C+ARC" data-count="horizontal" data-text="Migrating your code to Objective-C ARC" data-url="http://blog.mugunthkumar.com/articles/migrating-your-code-to-objective-c-arc/" data-lang="eng" data-via="@mugunthkumar" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></li><li><g:plusone size= "medium" href= "http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fmigrating-your-code-to-objective-c-arc%2F"></g:plusone></li><li><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fmigrating-your-code-to-objective-c-arc%2F&layout=button_count&show_faces=true&action=like&font=segoe ui&colorscheme=light&width=350&scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:25px;" allowTransparency="true" ></iframe></li></ul>
<p>Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/' rel='bookmark' title='MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions'>MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions</a> <small>MKStoreKit started off in a pet project a couple of...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.mugunthkumar.com/articles/migrating-your-code-to-objective-c-arc/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>iOS Tutorial: Advanced Networking with MKNetworkKit</title>
		<link>http://blog.mugunthkumar.com/coding/ios-tutorial-advanced-networking-with-mknetworkkit/</link>
		<comments>http://blog.mugunthkumar.com/coding/ios-tutorial-advanced-networking-with-mknetworkkit/#comments</comments>
		<pubDate>Mon, 19 Dec 2011 11:00:13 +0000</pubDate>
		<dc:creator>Mugunth Kumar</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Featured Articles]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[mknetworkkit]]></category>
		<category><![CDATA[nsmutableurlrequest]]></category>
		<category><![CDATA[nsurlconnection]]></category>

		<guid isPermaLink="false">http://blog.mugunthkumar.com/?p=1411</guid>
		<description><![CDATA[Couple of weeks ago, I wrote a clean, fast networking toolkit for iOS and Mac written for the LLVM Compiler 3.0 with ARC. Reception was very good that it was the &#8220;most-watched&#8221; repository on Github last week. Early adopters have sent me innumerable emails on how fast their network operations are, and how responsive their [...]
Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/coding/ios-tutorial-image-cache-and-loading-thumbnails-using-mknetworkkit/' rel='bookmark' title='iOS Tutorial: Image Cache and Loading Thumbnails using MKNetworkKit'>iOS Tutorial: Image Cache and Loading Thumbnails using MKNetworkKit</a> <small>If you have been following me on Twitter or reading...</small></li>
<li><a href='http://blog.mugunthkumar.com/products/ios-framework-introducing-mknetworkkit/' rel='bookmark' title='iOS Framework: Introducing MKNetworkKit'>iOS Framework: Introducing MKNetworkKit</a> <small>How awesome would it be if a networking framework automatically...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>Couple of weeks ago, I wrote a <a href="http://blog.mugunthkumar.com/products/ios-framework-introducing-mknetworkkit/">clean, fast networking toolkit for iOS and Mac</a> written for the LLVM Compiler 3.0 with ARC.<br />
Reception was very good that it was the &#8220;most-watched&#8221; repository on Github last week. Early adopters have sent me innumerable emails on how fast their network operations are, and how responsive their app is after integrating MKNetworkKit.<br />
MKNetworkKit is faster (and it makes your app feel smoother and faster with seamless transparent caching) in reality. There are two things that makes MKNetworkKit faster.<br />
First, it&#8217;s ARC based and the awesome LLVM 3.0 compiler brings in a ton of performance benefits. Using the @autoreleasepool block instead of NSAutoReleasePool in MKNetworkOperation alone should improve the performance by a huge factor (Apple claims it to be 6 times faster). If you still haven&#8217;t migrated to ARC because you want to support those iOS 3.x users, read <a href="http://mattgemmell.com/2011/12/05/latest-version/">this post</a> by Matt Gemmell first.</p>
<p>Second important performance benefit is seamless and transparent caching. By transparent caching, I mean, caching that involves zero overhead from the developer (That&#8217;s you).</p>
<p>Let me, in this post, brief you about how this seamless caching might help you. First, an example. You are refreshing a twitter stream. A GET request for that looks similar to</p>
<p>GET http://twitter.com/mugunthkumar/statuses</p>
<h2>Caching your responses, the wrong way</h2>
<p>Some developers cache responses using Core Data. <strong>STOP IT</strong></p>
<blockquote><p>Using Core Data for caching is like using the military to kill bedbugs in your bedroom. DON&#8217;T DO IT.</p></blockquote>
<p>The problem when you implement Core Data is, you should program your view controllers to work with two kinds of data structures. One, JSON/XML from server and the other, Core Data NSManagedObjects. Some &#8220;clever&#8221; developers &#8220;take it to the next level&#8221; by just programming their view controllers to work with only Core Data. The design goes like this. The network layer talks to the server and updates Core Data Store. Once the store is updated, send a NSNotification to &#8220;refresh&#8221; view controllers.<br />
This may sound clever to many. But it&#8217;s completely WRONG. I REPEAT. COMPLETELY WRONG. Core Data (or even structured SQL storage) is not meant for that. Core Data is a structured storage for persisting/serializing Object graphs in your application. Don&#8217;t use it for storing objects that have a low life time. Thumbnail images, list of tweets etc., just don&#8217;t belong there. Secondly, this would require you to read and write to flash memory on the iDevice which have a limited read/write cycle. Finally, reading and writing to disk (in this case, Core Data) is a very ugly way to transfer data from one class to another (in this case, from your Network Layer to View Controllers)</p>
<h2>Say hello to MKNetworkKit</h2>
<p>MKNetworkKit calls the SAME completion handler with cached data if you are making the call for the second time. When the network connectivity is proper, MKNetworkKit calls your completion handler twice. First with the cached data and again after fetching the latest data from server. As such, you can design your view controllers to work with just ONE kind of data, data from server. If you have an app that doesn&#8217;t cache and doesn&#8217;t work offline, just replace your networking library with MKNetworkKit and you get caching for free. Not even a single line of code change is required on your view controllers. Caching is transparent. Your view controllers needs to work with the same data structure, no matter whether the data is from cache or server.</p>
<h3>Behind the scenes</h3>
<p>MKNetworkKit caching is super light-weight and it caches your responses in a NSMutableDictionary. Doesn&#8217;t that lead to high memory usage? Yes. of-course, but MKNetworkKit is clever. It observes the UIApplicationDidReceiveMemoryWarningNotification and flushes the dictionary to disk. The next time you make a request to the cached URL, the cached data is brought back to memory. So in-effect, it has a in-memory cache and disk cache and uses a least recently used algorithm to flush items to disk. The MKNetworkEngine class has methods that can be over-ridden to control the cache cost.</p>
<p>Just override the method</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span> cacheMemoryCost;</pre></div></div>

<p>and return a higher/lower value based on your application&#8217;s requirements.</p>
<p>MKNetworkKit caching works like a intermediate proxy server by intercepting the response headers. So, when a second GET request to the same URL is made, MKNetworkKit behaves the following way.</p>
<p>1) For GET requests that sent a ETag in the header previously (for example, requests to Amazon S3 servers), MKNetworkKit sends a second request as a HEAD request (even if you specify as GET) with IF-NONE-MATCHheader. Most servers that send ETag (like Amazon S3) responds to IF-NONE-MATCH by sending the real data only when it has been changed. Otherwise, they return a 304 Not Modified which MKNetworkKit safely ignores. So data transfer is really not huge. Even this request is honored only after 1 day. So, repeated requests to the same thumbnail image doesn&#8217;t even hit the server.</p>
<p>2) For any GET request that contained a Cache-Control:max-age=in the header, MKNetworkKit honors that and makes the second request only after the expiry date. For dynamically generated requests, you should set Cache-Control on server. This not only helps MKNetworkKit, but most proxy servers along the way.</p>
<p>3) For requests that contained a Last-Modified field in the header, MKNetworkKit sends a &#8220;IF-MODIFIED-SINCE&#8221; HEAD request. This again works like the IF-NONE-MATCH. The server, either sends the complete data or a 304 Not Modified.</p>
<p>4) For servers that implement Cache-Control: no-cache, MKNetworkKit goes one step ahead and makes a second request only after a minute (60 sec). So repeated refreshes to often refreshed page will not exactly hit the server. For example, refreshing foursquare check-ins. It&#8217;s rare for these information to change within the next 60 sec.</p>
<p>5) For performance reasons, when the response type is an image, and the response headers doesn&#8217;t have any cache control information, MKNetworkKit assumes an expiry date of 7 days.</p>
<p>The last two are not an RFC standard. But these optimizations make network operations fast on a mobile devices even if the server isn&#8217;t implemented in an optimized way. All POST, PUT, HEAD and DELETE requests are ignored and not cached.</p>
<p>And, of course, you can customize all these behaviors by editing the values in MKNetworkKit.h</p>
<h2>Freezing Operations</h2>
<p>Another very important feature of MKNetworkKit is operation freezing. Imagine that, your customer take an awesome photo with your own &#8220;Instagram-killer&#8221; app, but since he is at a remote exotic place, 3G connectivity is poor and uploading the photo fails. Without MKNetworkKit, you should remember the photo related meta data, store the photo&#8217;s NSData in a file and upload the operation the next time the app is launched. Painful!<br />
With MKNetworkKit, you mark the photo upload operation is &#8220;freezable&#8221;. This means, in the event of network failure, your operations are automatically serialized (frozen beneath snow) and restored the next time the app launches, all for free.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">MKNetworkOperation <span style="color: #002200;">*</span>op <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>myEngine operationWithPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;/imageUpload&quot;</span> params<span style="color: #002200;">:</span>paramsDict httpMethod<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;POST&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>op setFreezable<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>; <span style="color: #11740a; font-style: italic;">// ONE EXTRA LINE</span>
<span style="color: #002200;">&#91;</span>myEngine enqueOperation<span style="color: #002200;">:</span>op<span style="color: #002200;">&#93;</span>;</pre></div></div>

<p>You can mark any POST/PUT/DELETE operation as freezable. GET operations are not freezable and MKNetworkKit ignores your call to setFreezable: if your operation is a &#8220;GET&#8221; operation.</p>
<h2>Advanced Tips</h2>
<h3>Friction-free authentication</h3>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">MKNetworkOperation <span style="color: #002200;">*</span>op <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>myEngine operationWithPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;/letmein&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>op setUserName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;mugunth&quot;</span> password<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;mYsEkReTpAsSwOrD&quot;</span><span style="color: #002200;">&#93;</span>; <span style="color: #11740a; font-style: italic;">// ONE EXTRA LINE</span>
<span style="color: #002200;">&#91;</span>op setUserName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;mugunth&quot;</span> password<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;mYsEkReTpAsSwOrD&quot;</span> basicAuth<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>; <span style="color: #11740a; font-style: italic;">// OR THIS LINE</span>
<span style="color: #002200;">&#91;</span>myEngine enqueOperation<span style="color: #002200;">:</span>op<span style="color: #002200;">&#93;</span>;</pre></div></div>

<p>When your server uses HTTP Basic auth or Digest auth or even Windows NTLM authentication, all you need to do is to set your username and password and MKNetworkKit auto-magically authenticates your request!. For NTLM authentication, just ensure your username is &#8220;domain\username&#8221;. There is no separate method setDomain: or something.</p>
<p>You can also set basicAuth:YES to send the credentials even before receiving the authentication challenge. However, this works only if your server uses HTTP Basic Authentication.</p>
<h3>Custom Authentication</h3>
<p>If your server uses HTML Form authentication, you can override the authHandler block and provide custom auth mechanisms.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">MKNetworkOperation <span style="color: #002200;">*</span>op <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>myEngine operationWithPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;/letmein&quot;</span><span style="color: #002200;">&#93;</span>;
op.authHandler <span style="color: #002200;">=</span> <span style="color: #002200;">^</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSURLAuthenticationChallenge</span> <span style="color: #002200;">*</span>cred<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span> 
<span style="color: #11740a; font-style: italic;">// show a web view controller or do whatever you want and finally, when you have a credentials ready, just call </span>
<span style="color: #002200;">&#91;</span>challenge.sender useCredential<span style="color: #002200;">:</span>credential forAuthenticationChallenge<span style="color: #002200;">:</span>challenge<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>;
<span style="color: #002200;">&#91;</span>myEngine enqueOperation<span style="color: #002200;">:</span>op<span style="color: #002200;">&#93;</span>;</pre></div></div>

<h3>Overriding MKNetworkEngine</h3>
<p>Tweaking the URL building methods with MKNetworkEngine is easy. Let me start by giving you an example. Imagine that you have a server which authenticates a logged in user and after authentication, it expects a Authorization header to be set with an access token.<br />
You need to have a <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">factory method</a> that creates URLs customized to your web service. This could include adding a authorization header in our case. You can do this by overriding the method,</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> enqueueOperation<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>MKNetworkOperation<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> operation;</pre></div></div>

<p>For example, in the above case, you can check your engine subclass for an access token and add it to the operation&#8217;s header in this method (if you have one).</p>
<h3>Overriding MKNetworkOperation</h3>
<p>Sometimes, you might do custom error handling based on the response from your server. For example, your server might send a valid HTTP response (status code 200) which could be an internal error, like &#8220;Invalid User&#8221;. Business logic errors are better handled with your own application level error codes. You overriding MKNetworkOperation to customize the success/failure reporting. I would highly recommend doing this along with designing your server to send error codes for error conditions.</p>
<p>The following methods are to be overridden for customizing error handling.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> operationSucceeded;
<span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> operationFailedWithError<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSError</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> error;</pre></div></div>

<p>For example, in the previous case, you can override operationSucceeded, inspect the response and if the response was indeed a business logic error (&#8220;Invalid User&#8221;), you can call the [super operationFailedWithError:[Your custom error class for "Invalid User"]];<br />
Otherwise, call [super operationSucceeded].</p>
<p>You can also override operationFailedWithError to introspect the actual cause of the error, if your server sends any error related information in the dictionary.</p>
<p>The reason for overriding at this level is to minimize error handling at view controller layer. So your presentation layer, UIViewController subclasses will be cleaner to read.</p>
<p>If you have subclassed the MKNetworkOperation and want the factory method in your engine subclass, operationWithURLString:params:httpMethod to prepare an operation of your subclass. To register your operation subclass with the engine, you can call the registerOperationSubclass: method.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> registerOperationSubclass<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">Class</span><span style="color: #002200;">&#41;</span> aClass;</pre></div></div>

<p>Your code fragment might look like,</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>self.myEngine registerOperationSubclass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>MyAppNetworkOperation class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;</pre></div></div>

<h3>Image Cache with MKNetworkEngine</h3>
<p>MKNetworkEngine has a handy method to load images from a server. It&#8217;s built-in cache mechanism ensures, your images are cached without using any third-party image cache libraries. That means your code base is even leaner.<br />
You can use the following method of MKNetworkEngine to load images.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> imageAtURL<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSURL</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>url onCompletion<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>MKNKImageBlock<span style="color: #002200;">&#41;</span> imageFetchedBlock;</pre></div></div>

<p>MKNKImageBlock is defined like this.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">typedef</span> <span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>MKNKImageBlock<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#40;</span>UIImage<span style="color: #002200;">*</span> fetchedImage, <span style="color: #400080;">NSURL</span><span style="color: #002200;">*</span> url, <span style="color: #a61390;">BOOL</span> isInCache<span style="color: #002200;">&#41;</span>;</pre></div></div>

<p>So your calling code will look like,</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">    <span style="color: #002200;">&#91;</span>ApplicationDelegate.myAppEngine imageAtURL<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> URLWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://example.com/image.png&quot;</span><span style="color: #002200;">&#93;</span> onCompletion<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span>UIImage <span style="color: #002200;">*</span>fetchedImage, <span style="color: #400080;">NSURL</span> <span style="color: #002200;">*</span>fetchedURL, <span style="color: #a61390;">BOOL</span> isInCache<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        self.imageView.image <span style="color: #002200;">=</span> fetchedImage;
    <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;</pre></div></div>

<p>If you are loading images onto a imageView inside a tableview cell, you can check if the completed URL is same as the passed URL</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">    <span style="color: #002200;">&#91;</span>ApplicationDelegate.myAppEngine imageAtURL<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> URLWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://example.com/image.png&quot;</span><span style="color: #002200;">&#93;</span> onCompletion<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span>UIImage <span style="color: #002200;">*</span>fetchedImage, <span style="color: #400080;">NSURL</span> <span style="color: #002200;">*</span>fetchedURL, <span style="color: #a61390;">BOOL</span> isInCache<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span>originalURL <span style="color: #002200;">==</span> fetchedURL<span style="color: #002200;">&#41;</span>
        cell.imageView.image <span style="color: #002200;">=</span> fetchedImage;
    <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;</pre></div></div>

<p>This check is necessary as tableview cells might be recycled and a cell might end up getting images from multiple network operations.</p>
<p>You might also want to read my other elaborate post on <a href="http://blog.mugunthkumar.com/coding/ios-tutorial-image-cache-and-loading-thumbnails-using-mknetworkkit/">Image Caching with MKNetworkKit</a></p>
<p>Lastly, if you are fading in your images like those fancy apps, add your fade-in logic if the image is loaded from server and not from cache.</p>
<h2>Source Code</h2>
<p><a href="https://github.com/MugunthKumar/MKNetworkKit">MKNetworkKit</a> on Github</p>
<p>MKNetworkKit might look simple, but it&#8217;s incredibly powerful. Use it in your apps and tell me how it scores. My next blog post would be on how to write a better RESTful server that serves a mobile device. Watch this space, subscribe to <a href="http://feeds.feedburner.com/MugunthKumar">my feed</a> or <a href="http://twitter.com/MugunthKumar">follow me on twitter</a>.</p>
<p>Interested in learning in-depth features of Objective-C and iOS? You should get my book.</p>
<p>Amazon - <a href="http://mk.sg/ios5book">http://mk.sg/ios5book<br />
</a></p>
<p>iBooks - <a href="http://mk.sg/ibook">http://mk.sg/ibook</a></p>
<p>Wiley &#8211; <a href="http://mk.sg/book">http://mk.sg/book</a></p>
<p>Book Depository &#8211; <a href="http://mk.sg/bdbook">http://mk.sg/bdbook</a><br />
&#8211;<br />
Mugunth</p>
<p><map name='google_ad_map_1411_8b86e81420c6776e'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/1411?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_1411_8b86e81420c6776e' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=1411&amp;url= http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fios-tutorial-advanced-networking-with-mknetworkkit%2F' /></p><p><a href ="http://twitter.com/mugunthkumar">Follow me </a> on Twitter</p><p>&copy;2012 <a href="http://blog.mugunthkumar.com">MKBlog</a>. All Rights Reserved.</p>.<h4 id="tweetandlike-heading"></h4><ul id="tweetandlike-buttons"><li><a href="http://twitter.com/share" data-title="iOS+Tutorial%3A+Advanced+Networking+with+MKNetworkKit" data-count="horizontal" data-text="iOS Tutorial: Advanced Networking with MKNetworkKit" data-url="http://blog.mugunthkumar.com/coding/ios-tutorial-advanced-networking-with-mknetworkkit/" data-lang="eng" data-via="@mugunthkumar" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></li><li><g:plusone size= "medium" href= "http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fios-tutorial-advanced-networking-with-mknetworkkit%2F"></g:plusone></li><li><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fios-tutorial-advanced-networking-with-mknetworkkit%2F&layout=button_count&show_faces=true&action=like&font=segoe ui&colorscheme=light&width=350&scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:25px;" allowTransparency="true" ></iframe></li></ul>
<p>Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/coding/ios-tutorial-image-cache-and-loading-thumbnails-using-mknetworkkit/' rel='bookmark' title='iOS Tutorial: Image Cache and Loading Thumbnails using MKNetworkKit'>iOS Tutorial: Image Cache and Loading Thumbnails using MKNetworkKit</a> <small>If you have been following me on Twitter or reading...</small></li>
<li><a href='http://blog.mugunthkumar.com/products/ios-framework-introducing-mknetworkkit/' rel='bookmark' title='iOS Framework: Introducing MKNetworkKit'>iOS Framework: Introducing MKNetworkKit</a> <small>How awesome would it be if a networking framework automatically...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.mugunthkumar.com/coding/ios-tutorial-advanced-networking-with-mknetworkkit/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Software philosophy: Release early, release often vs polished releases</title>
		<link>http://blog.mugunthkumar.com/articles/software-philosophy-release-early-release-often-vs-polished-releases/</link>
		<comments>http://blog.mugunthkumar.com/articles/software-philosophy-release-early-release-often-vs-polished-releases/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 12:00:36 +0000</pubDate>
		<dc:creator>Mugunth Kumar</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[philosophy]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://blog.mugunthkumar.com/?p=1298</guid>
		<description><![CDATA[Release early, release often is a philosophy where you release the product as soon as possible and rapidly iterate it to perfection by listening to your customers. A polished release, on the other hand is where your product, in its initial version is solid, lacks obvious bugs and has just enough features to satisfy a [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://en.wikipedia.org/wiki/Release_early,_release_often">Release early, release often</a> is a philosophy where you release the product as soon as possible and rapidly iterate it to perfection by listening to your customers. A polished release, on the other hand is where your product, in its initial version is solid, lacks obvious bugs and has just enough features to satisfy a majority of your consumers. Most software companies adopt either one of this and that choice is not superficial. In fact, it roots down to the heart of the company&#8217;s ideologies.<br />
Before you launch your next big product, website, app, read this and decide which side you are on.</p>
<h2>Philosophy followed by them</h2>
<p>Release early, release often, has always been the mantra of Linux kernel, software from Microsoft and plenty other open source software. Microsoft (and Microsoft developers) followed this philosophy since its inception. The Windows Operating System, in the initial version (1.0) did not support overlapping windows which was a breakthrough feature on the then contemporary Macintosh. Despite that, a few years later, Microsoft was able to catch up with the competition by following the release early, release often philosophy. In 1995, the same race happened between Microsoft and Netscape with browsers. IE 1.0 was no where near Netscape, but a couple of years later, the fourth iteration of the browser, IE 4 nailed it.</p>
<p>In late 90s, when the web became popular, updating your software (web application) became even easier and web application developers, continued to follow the same mantra. </p>
<p>The workflow of a web developer used to be like this.</p>
<p>Make a shitty website<br />
Improve your website<br />
check your visitor count<br />
…<br />
Improve your website<br />
check your visitor count<br />
…<br />
…<br />
Once your reach a satisfactory level, mark your release as final (remove that beta/gamma tag).</p>
<p>Later in 2004, when Google introduced their Gmail, it was known for the perpetual beta in the logo.<br />
Flickr moved from alpha to beta to gamma(!) in 2006!</p>
<h2>Philosophy followed by Apple</h2>
<p>Apple on the other hand polish their products to perfection. May be it&#8217;s their &#8220;Think different&#8221; culture or may be it&#8217;s the ingrained attitude of the late founder, Steve Jobs, to make &#8220;insanely great&#8221; products relegating profits or business strategies.</p>
<p>The first version of iOS (then called as iPhone OS), did not even have MMS, included in even the dumbest phones out there. Yet, every feature that was available, worked really really well. The first iPod, despite being available only for Mac users, was a runaway success.</p>
<h2>Consumer mindset outside of Software</h2>
<p>Let&#8217;s for a moment think outside of Software. Let&#8217;s take movies for example. Every single release of a movie, whether it is The Jurassic Park and its sequels or The Matrix and its sequels or Steve Jobs&#8217;s own Toy Story and its sequels never had &#8220;versions&#8221;.<br />
The movies were great right from the first release and the producers and directors never &#8220;planned&#8221; to make their movie incrementally better. Of course there were sequels, but they were not &#8220;bug fixes&#8221; or incremental updates to the original movie. The same holds good for physical commodities like cars or cameras. Remember, the world had cars, cameras and movies, much before Software. So, how and why did people got accustomed to this way of life, when it comes to Software? Will you accept if your new car, in its &#8220;version 1.0&#8243; doesn&#8217;t speed up beyond 60? Will you accept if the car manufacturer promises a free  &#8220;engine update&#8221; in the &#8220;near future&#8221;?</p>
<p>The reason was partly because, at least in the past, software was considered &#8220;Magical&#8221;. The first spreadsheet program (Lotus 1-2-3) can &#8220;sort&#8221; the marks of student in ascending order and made the process of calculating the rank among students in a class, super easy, fast and reliable. What usually took days, was accomplished within seconds using Software. Other commodities did not provide this level of satisfaction. </p>
<p>When something performs well on one area, human beings tend to be lenient in evaluating its performance else where. That &#8220;something&#8221; can be anything. <a href="http://www.youtube.com/watch?v=7xYkiN4-gl8">A beautiful blonde girl who is &#8220;not so smart&#8221;</a> or a restaurant that serves tasty food, but looks shoddy (or the other way round). This is precisely what happened to user&#8217;s perception of Software decades ago and unfortunately, has been continuing till now. A software that does one thing (sorting in this case) properly, but crashes often was still acceptable.</p>
<h2>How Apple changed your consumers</h2>
<p>Apple, on the other hand, tend to think different<strong>ly</strong><em></em>. They never use the &#8220;beta&#8221; tag. (And when they do, it is <a href="http://www.youtube.com/watch?v=SHoukZpMhDE">still better than the competition</a>). Look at the iterative changes that happens to any of their product. It, mostly remains same. The first iPod, still looks closely similar to the latest generation iPod classic and the first iPhone looks closely similar to the latest iPhone, the iPhone 4S and Mac OS X 10.0, looks closely similar to Mac OS X Lion. Leave software, even the light bulb invented by Edison a century ago, looks very similar in shape and size compared to the tungsten filament light bulb today. Contrarily, compare that to the control panel on Windows 95 to Windows 7 and the upcoming Windows 8 beta. It&#8217;s clear that, Microsoft didn&#8217;t nail it and they <strong>still</strong> haven&#8217;t nailed it.</p>
<p>With iPod, iPhone, iPad and several other products, Apple has proved that, Software can be done right, right from the initial version and has re-wired users&#8217; brain to expect quality products even when it is Software. This can be seen on the ratings of same apps from the same companies on Apple App Store and Android Market Place. Ratings on Market Place is usually higher than on App Store even if the Android version is buggier. Apple users expect quality. They don&#8217;t tolerate sh*t.</p>
<p>These two philosophical differences might have stemmed from the thought process of Steve Jobs and Bill Gates who shaped the early software industry. Steve was a perfectionist. Anything less than the ultimate is a shitty product. Bill on the other hand was different. He was more focussed on the monetary aspects of things (that doesn&#8217;t automatically mean it&#8217;s bad) at the expense of quality. </p>
<h2>What should you do?</h2>
<p>The release early, release often mantra has created a notion that Software is unreliable and often buggy. Since most software are like that, consumers, more than not, aren&#8217;t willing to pay for Software just as easy as they would for anything else. When we learn this, we complain that, their attitude is wrong. We even go as far as comparing the cost of a Starbucks coffee to an app and say people don&#8217;t pay for software that costs a fraction of the price of a coffee. It&#8217;s not that people don&#8217;t want to pay. It&#8217;s more like, people are not interested in paying for something that they are afraid, might not work as advertised. To consumers, buying a software is more like taking a risk than buying a coffee. With Windows, the risk was viruses. With online, cloud only, web applications, it was privacy. With App Store, Apple has shown them, what trustworthy computing is mitigating a huge risk considerably. With App Store, the risk a customer takes is paying for a software that doesn&#8217;t work as advertised (or doesn&#8217;t meet the quality expectations).</p>
<p>While Apple was not doing well in late 90s, the industry thrived well on release early, release often mantra. It often worked since, funding the software product was easy when it was iteratively developed. But, it&#8217;s 2011 now. If you are making a iOS app, remember that your target audience are iPhone/iPad users. They don&#8217;t tolerate sh*t. The App Store is filled with high quality apps and if your app doesn&#8217;t meet that quality expectations, don&#8217;t expect a run away success.  Make a polished product from day 1. If you are running low on budget/funding, don&#8217;t write software in the first place. If you were a movie producer, you can&#8217;t make a movie with half the money, release it and build upon that. Neither movies, nor cars or any other commodities are made like that. Don&#8217;t make a 0.8b release and expect users to tolerate it. Don&#8217;t promise *big* features on upcoming release. Some companies that I admire are Tapbots, Panic Software (they make the awesome FTP client, Transmit), AgileBits (the guys behind 1password). All of their products are &#8220;insanely great&#8221; right from day 1. Just because, something can be changed easily, doesn&#8217;t mean you should be changed frequently (iterated) even after release. Movies too had iterations, and cars had prototypes, but they existed only within the studio or the factory and never made it to the customers. You and me, the common man, doesn&#8217;t even know of their existence. Why can&#8217;t we build software like that? Why should you ship a product that&#8217;s not complete?</p>
<p>Let&#8217;s kill the notion that software can be made great <strong>only</strong> by rapid iteration. Make your next product an example of that.</p>
<p>&#8211;<br />
Mugunth</p>
<p><map name='google_ad_map_1298_8b86e81420c6776e'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/1298?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_1298_8b86e81420c6776e' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=1298&amp;url= http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fsoftware-philosophy-release-early-release-often-vs-polished-releases%2F' /></p><p><a href ="http://twitter.com/mugunthkumar">Follow me </a> on Twitter</p><p>&copy;2012 <a href="http://blog.mugunthkumar.com">MKBlog</a>. All Rights Reserved.</p>.<h4 id="tweetandlike-heading"></h4><ul id="tweetandlike-buttons"><li><a href="http://twitter.com/share" data-title="Software+philosophy%3A+Release+early%2C+release+often+vs+polished+releases" data-count="horizontal" data-text="Software philosophy: Release early, release often vs polished releases" data-url="http://blog.mugunthkumar.com/articles/software-philosophy-release-early-release-often-vs-polished-releases/" data-lang="eng" data-via="@mugunthkumar" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></li><li><g:plusone size= "medium" href= "http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fsoftware-philosophy-release-early-release-often-vs-polished-releases%2F"></g:plusone></li><li><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fsoftware-philosophy-release-early-release-often-vs-polished-releases%2F&layout=button_count&show_faces=true&action=like&font=segoe ui&colorscheme=light&width=350&scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:25px;" allowTransparency="true" ></iframe></li></ul>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.mugunthkumar.com/articles/software-philosophy-release-early-release-often-vs-polished-releases/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Singleton ain&#8217;t bad after all</title>
		<link>http://blog.mugunthkumar.com/articles/singleton-aint-bad-after-all/</link>
		<comments>http://blog.mugunthkumar.com/articles/singleton-aint-bad-after-all/#comments</comments>
		<pubDate>Thu, 11 Aug 2011 10:25:40 +0000</pubDate>
		<dc:creator>Mugunth Kumar</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://blog.mugunthkumar.com/?p=1217</guid>
		<description><![CDATA[On the Inter-webs, it&#8217;s very easy to find a piece of code that abuses singletons or a blog post that bitches why singletons are bad. Trust me, singletons are not bad. A singleton is a double edged sword. It&#8217;s up to you to use it the way it was intended to be used. In this post, [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p></p><p>On the Inter-webs, it&#8217;s very easy to find a piece of code that abuses singletons or a blog post that bitches why singletons are bad. Trust me, singletons are not bad. A singleton is a double edged sword. It&#8217;s up to you to use it the way it was intended to be used. In this post, I&#8217;ll talk about some often encountered problems where singletons are used in a wrong way and then provide you suggestions on how to overcome them.</p>
<p>While the examples I give here are iOS specific, Singleton is a design pattern. That means, you could apply this knowledge in pretty much any programming language.</p>
<h2>Common <span style="text-decoration: line-through;">(ab)</span>use cases for a Singleton</h2>
<p>You might find situations when you need to store the global state of the application somewhere. To store this state let&#8217;s create a singleton class called XYZManager.</p>
<p>The other common use case is you need a class that will probably be used inasmuch as every view of your application. So, let&#8217;s use a singleton.</p>
<p>Fortunately or unfortunately, using a singleton seems to solve both these problems, but will end you up in hot soup sometimes later during the project&#8217;s lifetime. Let&#8217;s see why.</p>
<h3><strong>Problem 1:</strong> Sharing global state</h3>
<p>If you find yourself in a situation where your app has lots of global state and every class reads/writes to this state, you have made a terrible mistake in designing your app.</p>
<p>A rule of thumb for a good object-oriented design is to limit global state variables. <strong>Using a singleton solely to store your state variables is as bad as using global variables in your app. A singleton is not designed for that.</strong></p>
<p>Of course, state variables cannot be completely removed in a software. Before you create such a variable, you should be doubly sure that the variable is truly global in your business domain.</p>
<h4>Example</h4>
<p>Let me give you an example. When you develop an app that talks to a web service, the only &#8220;state&#8221; variable I could think of is your access token. Using a Singleton to encapsulate calls to web service that remembers the access token is fine. But if you store the response strings from one method and use it in another method and then release it in yet another method, you are doing it wrong.</p>
<p>Let me quote a common example of this from iOS. You have a master-detail view. The details view can be reached only from the master view. The details view has an &#8220;Up/Down&#8221; segmented button that shows the previous/next content without having the user go back and forth. So let&#8217;s fetch the detailed content on a background thread and store it in a NSMutableArray in our singleton and whenever next button is tapped, increment the current index and update the UI. Neat and elegant, right? WRONG. It&#8217;s not the singleton&#8217;s responsibility to store data required by a few of the view controllers in your app. The problem with this method is, you cannot make an educated guess on when to release this NSMutableArray. A &#8220;clever&#8221; technique is to release it when the master view is unloaded. But then these &#8220;techniques&#8221; tightly couple the singleton with view controllers and affects reusability. Later on, if your business requirements change and you have to use the detailed view elsewhere, you will not be able to.</p>
<p>Another case is when you write a method in a singleton assuming that, so-and-so variable will have so-and-so values, when the control reaches there. If you have done this, you have tightly coupled your singleton with various other classes. This is something that&#8217;s very very hard to unit test.</p>
<p>Finally, because <strong>singletons don&#8217;t die</strong> and live till the end of the program, storing chunks of data like this results in a potential memory leak.</p>
<p><span class="Apple-style-span" style="font-size: 15px; font-weight: bold;"><strong>Problem 2:</strong> Managing state externally</span></p>
<p>A singleton&#8217;s state should be managed by one and only one class, self. If a view controller or another class changes the internal state variables of a singleton, you are doing it wrong. The getters of the singleton&#8217;s state variables can be public, but the setters should always be private. A good example from Cocoa is <a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html">UIDevice class</a>. It manages a wealth of state about the device, but nearly every state is marked readonly. When a state is changed, it often something that controls the behavior of the singleton.</p>
<p>If a singleton doesn&#8217;t manage any state, then you don&#8217;t actually need a singleton. What you need is a <a href="http://en.wikipedia.org/wiki/Facade_pattern">Façade object</a>.</p>
<h3><strong>Problem 3:</strong> Dependent singletons</h3>
<p>In your app, it&#8217;s &#8220;kinda&#8221; ok to have &#8220;too many&#8221; singletons, but ensure that they don&#8217;t talk to each other directly or indirectly. For example, you can have a FacebookManager, a TwitterManager and several other similar manager classes., but they shouldn&#8217;t communicate with each other. In other words, a singleton shouldn&#8217;t call methods in another singleton. For example, a method named, publishFeed in FacebookManager shouldn&#8217;t call publishTweet of TwitterManager. If you are doing this and cannot find a way out of this, merge them into one singleton. After all, they probably might be the &#8220;same&#8221; in your business domain. When you refactor considering this, you will find that your project with &#8220;too many&#8221; singletons actually has only one or two &#8220;real&#8221; singletons.</p>
<p>Another reason why you shouldn&#8217;t depend on a singleton method from another singleton is that, singletons are lazily loaded. You have no authoritative way to ascertain the order in which they are initialized (or the order in which they are torn down).</p>
<h3><strong>Problem 4:</strong> Delegates in a singleton</h3>
<p>Asingleton is a global class. No one single class should &#8220;own&#8221; the delegate of a singleton. To notify state changes, observe them through <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueObserving/">KVO</a> or <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotification_Class/Reference/Reference.html">NSNotificationCenter</a>. PS: The very first version of <a href="http://blog.mugunthkumar.com/coding/iphone-tutorial-–-in-app-purchases/">MKStoreKit</a> had this problem.</p>
<h4>Mediator Pattern</h4>
<p>If you still need two singletons to talk to each other, yet being independent, write a <a href="http://en.wikipedia.org/wiki/Mediator_pattern">mediator</a> class that handles this communication. Like in our previous case, if we have a FacebookManager and a TwitterManager and you want to publish an entry with one method call, write a mediator that &#8220;knows&#8221; how to publish to Facebook and how to publish to Twitter.</p>
<h2>Ok, nuff said, When should I use singletons then?</h2>
<p>Now that we know when not to use a singleton, let&#8217;s talk about some cases where you should be using them.</p>
<h2>Singletons are good</h2>
<p>Singletons are actually good, if you use them the right way. Every framework you have ever used, has a handful of singleton classes. iOS too have a few. UIDevice, UIApplication are some example. When you program for iOS, just look at how Apple uses them. A quick rule of thumb for your reference.</p>
<ol>
<li>Never change the state of a singleton from a class/method outside it.</li>
<li>Never allow two or more singletons to talk to each other.</li>
<li>Never write a method in a singleton that assumes/expects the state of a variable to be set to a particular value by another method. That&#8217;s methodB shouldn&#8217;t mandate that methodA should be called before it&#8217;s called.</li>
</ol>
<p>Only a class that&#8217;s truly a singleton in your business domain will satisfy all these points. If any one of the above point sounds illogical to you, what you need is something else and not a singleton.</p>
<p>Thus, Singletons ain&#8217;t bad after all. If you are convinced, pick up my <a href="http://blog.mugunthkumar.com/coding/objective-c-singleton-template-for-xcode-4/">Xcode 4 singleton template</a>.</p>
<p>&#8211;<br />
Mugunth</p>
<p><map name='google_ad_map_1217_8b86e81420c6776e'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/1217?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_1217_8b86e81420c6776e' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=1217&amp;url= http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fsingleton-aint-bad-after-all%2F' /></p><p><a href ="http://twitter.com/mugunthkumar">Follow me </a> on Twitter</p><p>&copy;2012 <a href="http://blog.mugunthkumar.com">MKBlog</a>. All Rights Reserved.</p>.<h4 id="tweetandlike-heading"></h4><ul id="tweetandlike-buttons"><li><a href="http://twitter.com/share" data-title="Singleton+ain%26%238217%3Bt+bad+after+all" data-count="horizontal" data-text="Singleton ain&#8217;t bad after all" data-url="http://blog.mugunthkumar.com/articles/singleton-aint-bad-after-all/" data-lang="eng" data-via="@mugunthkumar" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></li><li><g:plusone size= "medium" href= "http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fsingleton-aint-bad-after-all%2F"></g:plusone></li><li><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fsingleton-aint-bad-after-all%2F&layout=button_count&show_faces=true&action=like&font=segoe ui&colorscheme=light&width=350&scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:25px;" allowTransparency="true" ></iframe></li></ul>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.mugunthkumar.com/articles/singleton-aint-bad-after-all/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using MKStoreKit in your apps</title>
		<link>http://blog.mugunthkumar.com/coding/using-mkstorekit-in-your-apps/</link>
		<comments>http://blog.mugunthkumar.com/coding/using-mkstorekit-in-your-apps/#comments</comments>
		<pubDate>Thu, 04 Aug 2011 02:32:11 +0000</pubDate>
		<dc:creator>Mugunth Kumar</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[in-app purchases]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mkstorekit]]></category>

		<guid isPermaLink="false">http://blog.mugunthkumar.com/?p=1210</guid>
		<description><![CDATA[MKStoreKit, as you probably know is a framework for implementing In App Purchases in your app. It supports virtually every feature you could tell and every business model you could (or even Lodsys) ever think of. It supports, Auto-renewable subscriptions, Consumables, non-renewable subscriptions, and good old non-consumables and a whole lot others. The biggest gripe [...]
Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/' rel='bookmark' title='MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions'>MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions</a> <small>MKStoreKit started off in a pet project a couple of...</small></li>
<li><a href='http://blog.mugunthkumar.com/coding/in-app-purchases-troubleshooting-code0-cannot-connect-to-itunes-store-skerrorunknown/' rel='bookmark' title='In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)'>In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)</a> <small>When using MKStoreKit or any other equivalent framework or regular...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>MKStoreKit, as you probably know is a framework for implementing In App Purchases in your app. It supports virtually every feature you could tell and every business model you could (or even Lodsys) ever think of. It supports, Auto-renewable subscriptions, Consumables, non-renewable subscriptions, and good old non-consumables and a whole lot others.</p>
<p>The biggest gripe among the developer community is that there is no easy to use, step by step guide on how to use it. There are reasons why I couldn&#8217;t publish one.</p>
<h2>Why no demo?</h2>
<p>First and foremost, a working demonstration app implementing MKStoreKit requires an app to be setup on AppStore and this app cannot obviously be published. Conversely, I cannot open source an app that makes money for me through In App Purchases.</p>
<p>If you have an App on iTunes Connect without publishing it, Apple will send you a polite email after 2 or 3 months asking you to publish. Failing which, they remove it for you and will no longer allow you to create an App by the same name. Deleting the app obviously removes associated In App Purchases and the demonstration code will no longer work. It simply doesn&#8217;t make sense to play cat and mouse with Apple and create dummy apps for a demonstration software.</p>
<h2> Design of MKStoreKit </h2>
<p>However, MKStoreKit has been designed keeping this in mind. The whole integration shouldn&#8217;t take more than an hour or so. Implementing the MKStoreKit into your app is as simple as 10 or 15 lines of code.</p>
<p><b>Step 1: Initialization</b> The first step is the initialize it in the AppDelegate using the code,</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>MKStoreManager sharedManager<span style="color: #002200;">&#93;</span>;</pre></div></div>

<p><b>Step 2: The Plist magic </b> The second step is to set up your configurations in the plist file, which I think is quite obvious. There are three keys in the plist, one containing an array of non-consumables, one containing an array of consumables and another an array of auto-renewable subscriptions.</p>
<p><b>Step 3: Configuring for Non consumables</b> Non-consumables need no extra configuration. Just enter the list of product ids in the plist file.</p>
<p><b>Step 4: Configuring for consumables </b> For Consumables, you need to tell MKStoreKit, which product it belongs to and the quantity it adds.<br />
For example, com.mycompany.myapp.eggbasket1 = 10 eggs, and com.mycompany.myapp.eggbasket2 = 100 eggs, you need to tell MKStoreKit that both these are the same product &#8220;Egg&#8221; and they add 10 and 100 eggs respectively.</p>
<p>This is precisely what the keys <strong>Count</strong> and <strong>Name</strong> stands for.</p>
<p><b>Step 5: (Auto-renewable subscriptions)</b> For auto-renewable subscriptions, you need to tell the subscription length. MKStoreKit automatically keeps track of subscription expiry and notifies you through NSNotificationCenter if they expire. Since, Apple doesn&#8217;t keep track of subscription length, it&#8217;s your responsibility (which MKStoreKit takes care of) as a developer to remember those subscription length somewhere in your app. </p>
<p><b>Step 6: (Shared Secret) </b> If you use auto-renewable subscriptions, you need to enter set your shared secret. You should do this in MKStoreKitConfigs.h. If you don&#8217;t do this step, MKStoreKit cannot notify you of subscription expiry. Shared Secret is used for subscription verification and it&#8217;s compulsory to set this if you use auto-renewable subscriptions.</p>
<p><b>Step 7: The real purchase</b><br />
The real purchase code is a one liner.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>MKStoreManager sharedManager<span style="color: #002200;">&#93;</span> buyFeature<span style="color: #002200;">:</span>&lt;strong&gt;<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;com.mycompany.myapp.feature1&quot;</span>&lt;<span style="color: #002200;">/</span>strong&gt; 
                                    onComplete<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span> purchasedFeature<span style="color: #002200;">&#41;</span>
     <span style="color: #002200;">&#123;</span>
         NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Purchased: %@&quot;</span>, purchasedFeature<span style="color: #002200;">&#41;</span>;
		<span style="color: #11740a; font-style: italic;">// provide your product to the user here.</span>
		<span style="color: #11740a; font-style: italic;">// if it's a subscription, allow user to use now.</span>
		<span style="color: #11740a; font-style: italic;">// remembering this purchase is taken care of by MKStoreKit.</span>
     <span style="color: #002200;">&#125;</span>
                                   onCancelled<span style="color: #002200;">:^</span>
     <span style="color: #002200;">&#123;</span>
         <span style="color: #11740a; font-style: italic;">// User cancels the transaction, you can log this using any analytics software like Flurry.</span>
     <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;</pre></div></div>

<p>Everything happens behind the scenes, automatically. For every kind of product, whether it&#8217;s a consumable or non-consumable, this code is same.</p>
<p><b>Step 8: Expiry notifications for auto-renewable subscriptions</b> Subscribing to subscriptions revoked notifications (only for auto-renewable subscriptions).</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">	<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNotificationCenter</span> defaultCenter<span style="color: #002200;">&#93;</span> addObserver<span style="color: #002200;">:</span>self 
selector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span> <span style="color: #002200;">&#40;</span>subscriptionExpired<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> 
name<span style="color: #002200;">:</span> kSubscriptionsInvalidNotification 
object<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;</pre></div></div>

<p>It&#8217;s the configuration part that&#8217;s hard. So, as I promised that was under 10 lines right? One line in your AppDelegate, 4 or 5 lines in your Store ViewController and 2 lines to listen for subscription expiry notification. That wasn&#8217;t hard, was it?</p>
<h2>Going forward</h2>
<h3> Lion </h3>
<p>MKStoreKit will soon be released with full support for Lion<br />
Currently, I think it should automatically work, though I haven&#8217;t tested it. If you are using it, do let me know.</p>
<h3> iCloud </h3>
<p> Adding iCloud integration. With iCloud, your purchases will be remembered on iCloud rather than Keychain, which means, you don&#8217;t need to restore transactions on every device. iCloud will do it for you automatically.</p>
<p>The code for this is ready, but the NDA prevents me to push it to Github. Wait till Sep 5th (hopefully)</p>
<p>If you have any other feature requests, or want me to look at your changes, do send me a pull request for the code on Github<br />
<a href="http://github.com/mugunthkumar/MKStoreKit">http://github.com/mugunthkumar/MKStoreKit</a></p>
<p>Hope MKStoreKit helps you and your business. Do consider a paypal donation to mugunth.kumar@gmail.com.</p>
<p>Thanks,<br />
&#8211;<br />
Mugunth</p>
<p><map name='google_ad_map_1210_8b86e81420c6776e'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/1210?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_1210_8b86e81420c6776e' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=1210&amp;url= http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fusing-mkstorekit-in-your-apps%2F' /></p><p><a href ="http://twitter.com/mugunthkumar">Follow me </a> on Twitter</p><p>&copy;2012 <a href="http://blog.mugunthkumar.com">MKBlog</a>. All Rights Reserved.</p>.<h4 id="tweetandlike-heading"></h4><ul id="tweetandlike-buttons"><li><a href="http://twitter.com/share" data-title="Using+MKStoreKit+in+your+apps" data-count="horizontal" data-text="Using MKStoreKit in your apps" data-url="http://blog.mugunthkumar.com/coding/using-mkstorekit-in-your-apps/" data-lang="eng" data-via="@mugunthkumar" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></li><li><g:plusone size= "medium" href= "http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fusing-mkstorekit-in-your-apps%2F"></g:plusone></li><li><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fusing-mkstorekit-in-your-apps%2F&layout=button_count&show_faces=true&action=like&font=segoe ui&colorscheme=light&width=350&scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:25px;" allowTransparency="true" ></iframe></li></ul>
<p>Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/' rel='bookmark' title='MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions'>MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions</a> <small>MKStoreKit started off in a pet project a couple of...</small></li>
<li><a href='http://blog.mugunthkumar.com/coding/in-app-purchases-troubleshooting-code0-cannot-connect-to-itunes-store-skerrorunknown/' rel='bookmark' title='In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)'>In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)</a> <small>When using MKStoreKit or any other equivalent framework or regular...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.mugunthkumar.com/coding/using-mkstorekit-in-your-apps/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions</title>
		<link>http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/</link>
		<comments>http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/#comments</comments>
		<pubDate>Fri, 08 Jul 2011 06:15:52 +0000</pubDate>
		<dc:creator>Mugunth Kumar</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[iap]]></category>
		<category><![CDATA[in-app purchases]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[ios 4]]></category>
		<category><![CDATA[ios 5]]></category>
		<category><![CDATA[lion]]></category>
		<category><![CDATA[mkstorekit]]></category>
		<category><![CDATA[objective c]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.mugunthkumar.com/?p=1180</guid>
		<description><![CDATA[MKStoreKit started off in a pet project a couple of years ago and I wrote the first version in 2009. Since then, it has seen tremendous adoption rates that, it has been the &#8220;go-to&#8221; framework for implementing In-App purchases in any iOS app today. On iOS 4.3, Apple added a new type of subscription framework [...]
Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/coding/using-mkstorekit-in-your-apps/' rel='bookmark' title='Using MKStoreKit in your apps'>Using MKStoreKit in your apps</a> <small>MKStoreKit, as you probably know is a framework for implementing...</small></li>
<li><a href='http://blog.mugunthkumar.com/coding/in-app-purchases-troubleshooting-code0-cannot-connect-to-itunes-store-skerrorunknown/' rel='bookmark' title='In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)'>In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)</a> <small>When using MKStoreKit or any other equivalent framework or regular...</small></li>
<li><a href='http://blog.mugunthkumar.com/articles/migrating-your-code-to-objective-c-arc/' rel='bookmark' title='Migrating your code to Objective-C ARC'>Migrating your code to Objective-C ARC</a> <small>Recently, Apple introduced several new developer stuff including Xcode 4,...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>MKStoreKit started off in a pet project a couple of years ago and I wrote the first version in 2009.<br />
Since then, it has seen tremendous adoption rates that, it has been the &#8220;go-to&#8221; framework for implementing In-App purchases in any iOS app today.</p>
<p>On iOS 4.3, Apple added a new type of subscription framework called, auto-renewable subscriptions.</p>
<p>Today, I&#8217;m adding this support to MKStoreKit along with several new features. If you have been following me on <a href="http://twitter.com/mugunthkumar">Twitter (@mugunthkumar)</a> or on <a href="http://github.com/mugunthkumar">Github</a>, you would have gotten the code a week ago.<br />
Now that, I&#8217;m done with my testing it&#8217;s finally ready for some real-world adoption in your projects.</p>
<h2>What&#8217;s New</h2>
<ol>
<li> The main feature includes support for Auto-renewable subscriptions.</li>
<li> The second important change is to move configuration related changes to a separate file,

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">MKStoreKitConfigs.h and
MKStoreKitConfigs.plist</pre></div></div>

<p>The plist contains a list of products you support and MKStoreKit automatically reads this and creates StoreKit requests on your behalf. This feature was partly inspired by a issue raised <a href="https://github.com/MugunthKumar/MKStoreKit/issues/6">here</a> by a contributor, <a href="https://github.com/dfabulich">dfabulich</a>. But I didn&#8217;t like adding a datasource to MKStoreKit for various reasons. I think this method is cleaner than that. MKStoreKit now behaves like a standalone drop-in package.</li>
<li> MKStoreKitDelegate removed in favour of Blocks</li>
<li> Keychain support using SFHFKeychainUtils<br />
<h2>How to use</h2>
<p>The most important change to MKStoreKit is the use of a plist file instead of Macro strings for your product ids.<br />
The following screenshot shows the plist file organization.<br />
<img title="MKStoreKitConfigs.plist.png" src="http://blog.mugunthkumar.com/wp-content/uploads/MKStoreKitConfigs.plist_.png" border="0" alt="MKStoreKitConfigs.plist" width="600" height="181" /><br />
There are three main sections, Consumables, Non-consumables and Subscriptions. You specify your product inside each category based on how you added them on iTunes connect.<br />
After that, MKStoreKit does the rest.<br />
Non-consumable and Subscriptions are straight forward. I think I might need to explain a bit about Consumable support.</p>
<p>Every consumable entry in this plist needs to be a dictionary with &#8220;Count&#8221; and &#8220;Name&#8221; defined. Imagine that your app is a fish tank app with eggs, plants and fishes as consumables. Fishes are going to be sold on a per-fish basis. However, you might be interested in selling eggs as discounted basket. To allow this business model, I&#8217;ve added a new entry called unique name to every consumable.</p>
<p>If your products, for example,</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">com.myfishapp.eggbasket50 <span style="color: #002200;">=</span> $2
com.myfishapp.eggbasket500 <span style="color: #002200;">=</span> $15
com.myfishapp.eggbasket5000 <span style="color: #002200;">=</span> $ <span style="color: #2400d9;">125</span></pre></div></div>

<p>are in fact same in your business (in this case they are all eggs, just that the count is different and subsidized for bulk purchases), you can define them on plist as individual consumable mapping to the same name.<br />
MKStoreKit will then treat all these products as same when remembering purchases.</p>
<p>So instead of you remember how many fish eggs this person has purchased, you can leave that task to MKStoreKit. You get a nice wrapper around them and call these methods on MKStoreKit</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span> canConsumeProduct<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> productName quantity<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span> quantity;</pre></div></div>

<p>to check for product availability and</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span> consumeProduct<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> productName quantity<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span> quantity;</pre></div></div>

<p>to notify MKStoreKit to deduct the consumable&#8217;s balance.</p>
<p>This support was originally added to MKStoreKit 3.5, but it didn&#8217;t support product bundles. MKStoreKit v4 adds support for this.</p>
<h2>Subscriptions expiry notification</h2>
<p>MKStoreKit automatically posts notifications when your auto-renewable subscriptions are renewed or failed validation (expired). Observe the following notifications,</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">kSubscriptionsPurchasedNotification
kSubscriptionsInvalidNotification</pre></div></div>

<p>on your view controller or AppDelegate and take corresponding actions.</p>
<h2>A note for MKStoreKit 3 users</h2>
<p>MKStoreKit 4 uses keychain to remember purchases. This is partly to support In-App purchases on the upcoming operating system, OS X Lion. On iOS, all apps are sand-boxed and outside access to NSUserDefaults is not possible (unless the device is jail-broken). So remembering purchases on NSUserDefaults was *good enough*. On Lion, however, NSUserDefaults file is just another plist that could be edited on any text editor and technically &#8220;buy&#8221; our in-app feature. To circumvent this piracy, MKStoreKit 4 will use keychain instead of NSUserDefaults.<br />
As such if you have any consumables, they will not be automatically migrated to keychain store by MKStoreKit. You should do that part yourself. Non-consumables and Subscriptions doesn&#8217;t have this issue.</p>
<h2>Source Code</h2>
<p>The complete source is available on <a href="http://github.com/MugunthKumar/MKStoreKit">Github</a></p>
<h2>Demo Project</h2>
<p>There isn&#8217;t a demo project available because of the nature in which In-App purchases work.<br />
The only way would be to create a dummy project from my iTunes store account and create IAP. But that would add maintenance nightmare for me. However, since MKStoreKit is self-contained, you shouldn&#8217;t normally have trouble integrating it into the product.</p>
<h2>Licensing</h2>
<p>It&#8217;s licensed under Zlib as I feel that&#8217;s the most open license ever.</p>
<h2>A word on third-party components</h2>
<p>MKStoreKit uses the following third-party components.</p>
<ol>
<li><a href="https://github.com/johnezang/JSONKit"> JSONKit </a> by John Engelhart (BSD or Apache Licensed)</li>
<li>NSData base64 encoding additions by <a href="http://cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html">Matt Gallagher</a> (Zlib license)</li>
<li><a href="https://github.com/ldandersen/scifihifi-iphone">SFHFKeychianUtils</a> by Buzz Andersen</li>
</ol>
<h2>Final words</h2>
<p>I&#8217;m still making some touchups and final set of changes. But I think they will mostly be *cosmetic* (code refactoring). Feel free to pull/fork MKStoreKit and leave your feedback.</p>
<h2>Support me</h2>
<p>Hourly rates of a iPhone developer is <a href="http://stackoverflow.com/questions/209170/how-much-does-it-cost-to-develop-an-iphone-application">skyrocket high</a>. I believe this code would have saved your coding hours by at least a day. You can consider supporting further development by funding me through <a href="https://www.paypal.com">PayPal</a>.  My PayPal email is mugunth.kumar@gmail.com<br />
&#8211;<br />
Mugunth</li>
</ol>
<p><map name='google_ad_map_1180_8b86e81420c6776e'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/1180?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_1180_8b86e81420c6776e' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=1180&amp;url= http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fmkstorekit-4-0-supporting-auto-renewable-subscriptions%2F' /></p><p><a href ="http://twitter.com/mugunthkumar">Follow me </a> on Twitter</p><p>&copy;2012 <a href="http://blog.mugunthkumar.com">MKBlog</a>. All Rights Reserved.</p>.<h4 id="tweetandlike-heading"></h4><ul id="tweetandlike-buttons"><li><a href="http://twitter.com/share" data-title="MKStoreKit+4.0+%26%238211%3B+Supporting+Auto+Renewable+Subscriptions" data-count="horizontal" data-text="MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions" data-url="http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/" data-lang="eng" data-via="@mugunthkumar" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></li><li><g:plusone size= "medium" href= "http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fmkstorekit-4-0-supporting-auto-renewable-subscriptions%2F"></g:plusone></li><li><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fmkstorekit-4-0-supporting-auto-renewable-subscriptions%2F&layout=button_count&show_faces=true&action=like&font=segoe ui&colorscheme=light&width=350&scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:25px;" allowTransparency="true" ></iframe></li></ul>
<p>Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/coding/using-mkstorekit-in-your-apps/' rel='bookmark' title='Using MKStoreKit in your apps'>Using MKStoreKit in your apps</a> <small>MKStoreKit, as you probably know is a framework for implementing...</small></li>
<li><a href='http://blog.mugunthkumar.com/coding/in-app-purchases-troubleshooting-code0-cannot-connect-to-itunes-store-skerrorunknown/' rel='bookmark' title='In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)'>In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)</a> <small>When using MKStoreKit or any other equivalent framework or regular...</small></li>
<li><a href='http://blog.mugunthkumar.com/articles/migrating-your-code-to-objective-c-arc/' rel='bookmark' title='Migrating your code to Objective-C ARC'>Migrating your code to Objective-C ARC</a> <small>Recently, Apple introduced several new developer stuff including Xcode 4,...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/feed/</wfw:commentRss>
		<slash:comments>135</slash:comments>
		</item>
		<item>
		<title>Designing usable mobile apps</title>
		<link>http://blog.mugunthkumar.com/articles/ui-considerations-mobile-vs-web/</link>
		<comments>http://blog.mugunthkumar.com/articles/ui-considerations-mobile-vs-web/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 11:06:30 +0000</pubDate>
		<dc:creator>Mugunth Kumar</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ui]]></category>
		<category><![CDATA[ui-design]]></category>
		<category><![CDATA[usability]]></category>
		<category><![CDATA[ux]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.mugunthkumar.com/?p=1004</guid>
		<description><![CDATA[Another usability related blog from me after a long time and now, it&#8217;s a mobile vs web debate. While not exactly a rant, I intend to bridge the gap between web designers and mobile designers. Information architecture on mobile In the web 2.0 era, not much thought or discussion was spent on how to organize [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p></p><div id="_mcePaste">Another usability related blog from me after a long time and now, it&#8217;s a mobile vs web debate. While not exactly a rant, I intend to bridge the gap between web designers and mobile designers.</div>
<h2>Information architecture on mobile</h2>
<div id="_mcePaste">In the web 2.0 era, not much thought or discussion was spent on how to organize your content on your website. Primary reason could be because, there were easier workarounds to get away with this. For example, you can add a site map or a search into your website, which effectively replaces the need for a great IA. While not every website can be benefitted by this, over 90% of the not so content rich sites can just work. (A quick question, how many of you use the sitemap of your company Intranet as your home tab url ?)</div>
<div id="_mcePaste">However, when it come to designing native apps for the mobile device, you have to focus more on IA by placing information/features at the right place. Designing the IA and the workflow of your product is far different from aesthetics. While aesthetics wins first time users, by setting your product apart, a cleaner navigation and/or a cleaner workflow is essential in making them permanent. Most designers, especially those who are experienced &#8220;web&#8221; designers just don&#8217;t seem to get this.  The primary reason for me to make this conjecture is after interacting with Flash developers who have a natural instinct to design great interfaces.</div>
<div id="_mcePaste">There are several reasons why I would advocate this. First and foremost, your iPhone app doesn&#8217;t have a &#8220;site map&#8221;. They neither have anything that&#8217;s remotely equivalent to a search engine which would magically land the user into the right page/view of your app. Hence, the onus lies on the interaction designer to develop a paradigm that best helps the user navigate through the app. If your user cannot navigate to; or locate a feature he wants on your app, he thinks that feature is just not there. If there are many such &#8220;features&#8221; that are &#8220;not present&#8221; according to the user, your app will be deleted with a 1 star rating.</div>
<h2>Aesthetics vs Interaction Design</h2>
<div id="_mcePaste">Now, most UI/UX designers (or those who claim to be) have a misconception that, UI design/aesthetics is the same as interaction design. Designing a workflow goes a long way into understanding the product well unlike designing the look and feel of the app. I would even go a step ahead and say that, aesthetics is not what that makes or breaks your app. It&#8217;s the user interaction or the workflow. While aesthetics wins first time users, by setting your product apart, a cleaner navigation and/or a cleaner workflow is essential in making them permanent.</div>
<div id="_mcePaste">Most designers might disagree with me here, but if you look at most successful iphone apps on the iPhone AppStore, like Facebook or Twitter they don&#8217;t even have a heavily themed UI.</div>
<h2>Custom themes/colors vs custom UI elements</h2>
<div id="_mcePaste">Unlike the web, when you design for a platform, companies have written excellent HIG documentation on how to design your UI so that it looks best on the device. Designers ought to follow these guidelines, since users  like apps that are similar to built in apps than those that are different. While a different, unique website gets more attention, its not the same when you write native apps. I&#8217;m not advocating against using custom interfaces like the <a href="http://readthefuckinghig.tumblr.com/">Read the Fucking HIG</a> site, but if you are using it, you should carefully evaluate and test the UI before releasing the app.</div>
<h2>Problems with a custom interaction pattern over HIG</h2>
<div id="_mcePaste">The horizontal scroller that was launched with Facebook, still present in the three20 library, is easily a classical example of a poorly implemented custom UI element. Even Facebook replaced it with the springboard user interface in 3.0 release. Should you use custom UI, ensure that it blends well with the native toolkits that users don&#8217;t even think its customized. Example of such a great implementation is tweetie&#8217;s customized tab bar. It doesn&#8217;t have tab title text and is thinner than the original,  which makes it great while the iPhone is used in landscape mode and has a glow instead of a red badge for indication. Do note that Loren did stick with the default colors in this heavily customized tab bar since any changes to those colors will affect the mental model of the user who has learnt that a blue tab means selected and gray is unselected.</div>
<div id="_mcePaste">Apple has spent zillions of man hours to get the colors right on the iPhone. Change the tint color only if it represents your brand, like how Facebook does. Use colorful tints, themes funky interface on bigger devices like the iPad and not the iPhone.</div>
<div id="_mcePaste">Highly successful and useful apps like Things, Twitter for iPhone, 1Password pro follow this. They do change the native colors and use a heavily customized UI  on the ipad equivalents. Success of your iPhone app is not even remotely related to aesthetics. While aesthetics is a good to have thing,  it&#8217;s too distracting on smaller devices like the iPhone. Use all your creativity when you develop the iPad app. Just look at the native calendar app on iPhone and iPad, you will understand what I&#8217;m talking about now.</div>
<h2>&#8220;Hint UI&#8221; text wastes precious space.</h2>
<div id="_mcePaste">Hint UI are those that float over your user interface explaining the user what he should do next.</div>
<div id="attachment_1051" class="wp-caption alignleft" style="width: 210px"><a href="http://blog.mugunthkumar.com/wp-content/uploads/App-showing-a-hint-text1.png"><img class="size-medium wp-image-1052 " title="App showing a hint text" src="http://blog.mugunthkumar.com/wp-content/uploads/App-showing-a-hint-text1-200x300.png" alt="" width="200" height="300" /></a><p class="wp-caption-text">Hint Text on a App Screenshot</p></div>
<div id="attachment_1054" class="wp-caption alignleft" style="width: 210px"><a href="http://blog.mugunthkumar.com/wp-content/uploads/beluga.png"><img class="size-medium wp-image-1054  " title="beluga" src="http://blog.mugunthkumar.com/wp-content/uploads/beluga-200x300.png" alt="" width="200" height="300" /></a><p class="wp-caption-text">Beluga, showing a &quot;friendly text&quot; </p></div>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Avoid them as far as possible on the iPhone app. You have only 416 pixels to play with (20 goes off for status bar and another 44 for the navigation bar). The screen size is too limited to carry all those noise elements. Again, this is a often used paradigm on the web by web designers trying to &#8220;help out&#8221; users. On any iPhone app there is just one call to action, usually on the top right corner or if it were a page with a toolbar, it would be four or five. You don&#8217;t need a hint overlays on iPhone. If you think, you need, your UI requires a complete overhaul.</p>
<div id="attachment_1051" class="wp-caption aligncenter" style="width: 210px"><a href="http://blog.mugunthkumar.com/wp-content/uploads/appsfire.png"><br />
</a><a href="http://blog.mugunthkumar.com/wp-content/uploads/appsfire.png"><img class="size-medium wp-image-1052 " title="App showing a hint text" src="http://blog.mugunthkumar.com/wp-content/uploads/appsfire-200x300.png" alt="" width="200" height="300" /></a><p class="wp-caption-text">A mini tutorial pops up at random meddling with your workflow</p></div>
<div>This app called, AppsFire, while looking extremely beautiful,interrupts workflow by showing a modal popup trying to help.</div>
<div>
<div id="attachment_1055" class="wp-caption aligncenter" style="width: 210px"><a href="http://blog.mugunthkumar.com/wp-content/uploads/bloomberg.png"><img class="size-medium wp-image-1055 " title="bloomberg" src="http://blog.mugunthkumar.com/wp-content/uploads/bloomberg-200x300.png" alt="" width="200" height="300" /></a><p class="wp-caption-text">Bloomberg&#39;s friendly text appears only when you interact with it</p></div>
</div>
<div>On the other hand, a &#8220;not so beautifully designed&#8221; app, Bloomberg, tells me to rotate the device to view a full screen graph which I tap on the small graph. Yes, it tells you only when you tap on it. May be the appsfire developers should have shown this &#8220;mini-tutorial&#8221; when I tap on the &#8220;firemeter&#8221;?</div>
<div>As I said before, designing usable needs a good understanding on how potential customers would be using your app. From your app, think about your users, and interaction design. Then think about making your app &#8220;sexy&#8221;.</div>
<div>Feel free to leave a comment if you agree/disagree with what I&#8217;ve written.</div>
<div>&#8211;</div>
<div>Mugunth</div>
<p><map name='google_ad_map_1004_8b86e81420c6776e'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/1004?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_1004_8b86e81420c6776e' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=1004&amp;url= http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fui-considerations-mobile-vs-web%2F' /></p><p><a href ="http://twitter.com/mugunthkumar">Follow me </a> on Twitter</p><p>&copy;2012 <a href="http://blog.mugunthkumar.com">MKBlog</a>. All Rights Reserved.</p>.<h4 id="tweetandlike-heading"></h4><ul id="tweetandlike-buttons"><li><a href="http://twitter.com/share" data-title="Designing+usable+mobile+apps" data-count="horizontal" data-text="Designing usable mobile apps" data-url="http://blog.mugunthkumar.com/articles/ui-considerations-mobile-vs-web/" data-lang="eng" data-via="@mugunthkumar" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></li><li><g:plusone size= "medium" href= "http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fui-considerations-mobile-vs-web%2F"></g:plusone></li><li><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fui-considerations-mobile-vs-web%2F&layout=button_count&show_faces=true&action=like&font=segoe ui&colorscheme=light&width=350&scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:25px;" allowTransparency="true" ></iframe></li></ul>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.mugunthkumar.com/articles/ui-considerations-mobile-vs-web/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Become a more productive iOS developer</title>
		<link>http://blog.mugunthkumar.com/articles/become-a-more-productive-ios-developer/</link>
		<comments>http://blog.mugunthkumar.com/articles/become-a-more-productive-ios-developer/#comments</comments>
		<pubDate>Tue, 01 Feb 2011 09:07:29 +0000</pubDate>
		<dc:creator>Mugunth Kumar</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://blog.mugunthkumar.com/?p=1000</guid>
		<description><![CDATA[If you are a iOS developer and make your daily bread by writing iOS apps, these are three software applications that can dramatically improve your productivity and quality of your coding. 1) Code Pilot My first favorite software is a XCode plugin called Code Pilot. It is a nifty plugin that, I would say, is [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p></p><p>If you are a iOS developer and make your daily bread by writing iOS apps, these are three software applications that can dramatically improve your productivity and quality of your coding.</p>
<h2>1) Code Pilot</h2>
<p><a href="http://blog.mugunthkumar.com/wp-content/uploads/Code-Pilot-easy-project-navigation-for-Xcode.png"><img class="size-medium wp-image-1012 alignleft" title="Code Pilot - easy project navigation for Xcode!" src="http://blog.mugunthkumar.com/wp-content/uploads/Code-Pilot-easy-project-navigation-for-Xcode-300x193.png" alt="" width="300" height="193" /></a></p>
<p>My first favorite software is a XCode plugin called Code Pilot. It is a nifty plugin that, I would say, is QuickSilver for XCode. Jump into a file, or a method within a file within a couple of keystrokes. It matches your keystroke with files in your project using a special regex that you can type ABCTVC for going to ABCTableViewController.h or you can type cellFIP for cellForRowAtIndexPath. Its really smart and really helpful and it doesn&#8217;t need any customization. Just install the plugin and you are good to go.</p>
<p>Get it here</p>
<p><a href="http://codepilot.cc/">http://codepilot.cc/</a></p>
<p>A drawback of this tool is that, it&#8217;s currently available only for XCode 3 and no information on XCode 4 support is known as of now.</p>
<h2>2) Accessorizer</h2>
<p><a href="http://blog.mugunthkumar.com/wp-content/uploads/accessorizerIcons-1-dragged.tiff"><img class="size-full wp-image-1011 alignleft" title="accessorizerIcons-1 (dragged)" src="http://blog.mugunthkumar.com/wp-content/uploads/accessorizerIcons-1-dragged.tiff" alt="" width="201" height="201" /></a></p>
<p>Writing Model classes for your project can never be this easy. Just write your class variables. Accessorizer automatically generates @property, @synthesize for you.</p>
<p>Accessorizer can also generate a variety of code blocks that includes Key-Value Coding, Keved Archiving, dealloc blocks, Case statements for enums, Singleton classes and a lot more. It also recognizes IBOutlets and generates viewDidUnload code for them. Accessorizer is a swiss army knife for a iOS developer.</p>
<p>Get it here</p>
<p><a href="http://www.kevincallahan.org/software/accessorizer.html">http://www.kevincallahan.org/software/accessorizer.html</a></p>
<p>It&#8217;s also available on <a href="http://itunes.apple.com/sg/app/accessorizer/id402866670?mt=12">Mac App Store</a>.</p>
<p>A drawback of this tool is that, it&#8217;s quite complicated to customize it initially and get things started. Early users, especially users who are new to iOS platform might be baffled with the number of available options and customizations in the software. Fear not, it isn&#8217;t that complicated as it seems. Once you set it up properly, it&#8217;s a breeze to generate code.</p>
<h2>3) SnippetsApp</h2>
<p><a href="http://blog.mugunthkumar.com/wp-content/uploads/Snippets-1-dragged.tiff"><img class="size-full wp-image-1013 alignleft" title="Snippets-1 (dragged)" src="http://blog.mugunthkumar.com/wp-content/uploads/Snippets-1-dragged.tiff" alt="" width="201" height="201" /></a>While there are many apps, both cheap and expensive ones, this particular app by Lucky Ants is the best in my view. You can create code snippets right from XCode, or insert code snippets from library into your project all within a couple of keystrokes. The work flow is just right for a user relying heavily on keyboard shortcuts.</p>
<p><a href="http://www.snippetsapp.com/">http://www.snippetsapp.com/</a></p>
<p>A drawback of this tool is that it doesn&#8217;t offer any kind of syncing of your code snippets across your devices as of now, although developers have promised a sync feature soon.</p>
<p><map name='google_ad_map_1000_8b86e81420c6776e'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/1000?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_1000_8b86e81420c6776e' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=1000&amp;url= http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fbecome-a-more-productive-ios-developer%2F' /></p><p><a href ="http://twitter.com/mugunthkumar">Follow me </a> on Twitter</p><p>&copy;2012 <a href="http://blog.mugunthkumar.com">MKBlog</a>. All Rights Reserved.</p>.<h4 id="tweetandlike-heading"></h4><ul id="tweetandlike-buttons"><li><a href="http://twitter.com/share" data-title="Become+a+more+productive+iOS+developer" data-count="horizontal" data-text="Become a more productive iOS developer" data-url="http://blog.mugunthkumar.com/articles/become-a-more-productive-ios-developer/" data-lang="eng" data-via="@mugunthkumar" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></li><li><g:plusone size= "medium" href= "http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fbecome-a-more-productive-ios-developer%2F"></g:plusone></li><li><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fbecome-a-more-productive-ios-developer%2F&layout=button_count&show_faces=true&action=like&font=segoe ui&colorscheme=light&width=350&scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:25px;" allowTransparency="true" ></iframe></li></ul>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.mugunthkumar.com/articles/become-a-more-productive-ios-developer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Porting iPhone/iOS apps to Windows Phone</title>
		<link>http://blog.mugunthkumar.com/articles/porting-iphoneios-apps-to-windows-phone/</link>
		<comments>http://blog.mugunthkumar.com/articles/porting-iphoneios-apps-to-windows-phone/#comments</comments>
		<pubDate>Tue, 07 Dec 2010 09:00:32 +0000</pubDate>
		<dc:creator>Mugunth Kumar</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[wp7]]></category>

		<guid isPermaLink="false">http://blog.mugunthkumar.com/?p=961</guid>
		<description><![CDATA[Few days ago, I wrote a post on my review on Windows Phone. While I have been a Microsoft basher (no not really), Windows Phone is one product that surprised me (and I think most other bloggers as well) and took the smart phone UI to the next level. While Microsoft has been known to [...]
Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/articles/ui-considerations-mobile-vs-web/' rel='bookmark' title='Designing usable mobile apps'>Designing usable mobile apps</a> <small>Another usability related blog from me after a long time...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>Few days ago, I wrote a post on my <a href="http://blog.mugunthkumar.com/tech/a-tryst-with-windows-phone-7/">review on Windows Phone</a>. While I have been a Microsoft basher (no not really), Windows Phone is one product that surprised me (and I think most other bloggers as well) and took the smart phone UI to the next level. While Microsoft has been known to make killer user interfaces like Microsoft Fluent UI aka Ribbon, and the famous Start Menu on Windows 95, they haven&#8217;t been doing much recently. While they don&#8217;t innovate fast enough like Apple, Windows Phone is a whole new innovative product that looks new, refreshing and even &#8220;threatening&#8221; to competition that, even Apple was forced to make some of its features like Find My Phone of MobileMe free.</p>
<h2>Windows Phone is the next major platform</h2>
<p>Windows Phone is all set to be the next major platform in the Mobile Space. While it will be second to Apple at least for several years to come, It&#8217;ll still garner market share from new smartphone users and competitors like Blackberry and Android. It should be noted that, even while Android is free and can be customized by device manufactures, most companies <a href="http://www.engadget.com/2010/11/19/sony-ericsson-france-ceo-says-windows-phone-7-handsets-arent-li/">except Sony Ericsson</a> have vouched for or shown some kind of support for this new Microsoft Operating System. <a href="http://www.wareground.com/articles/samsung_to_make_more_windows_phone_7_handsets_than_android_ones_next_year">Samsung will be shipping more Windows Phone devices</a> than Android (and even it&#8217;s own Bada) in 2011, while <a href="http://www.engadget.com/2010/10/06/motorola-is-open-to-developing-windows-phone-7-devices-but-on/">Motorola is interested in making Windows Phone</a> devices despite lawsuit. Given all these, as successful developers, I strongly think it&#8217;s high time to start porting apps to Windows Phone. Even the mighty <a href="http://twitter.com/#!/RovioMobile/status/7192561399635968">Rovio Mobile is making a Windows Phone 7 port</a> of Angry Birds <a href="http://twitter.com/#!/roviomobile/status/26940229275">after dissing Microsoft</a>. More info <a href="http://www.intomobile.com/2010/11/24/angry-birds-coming-to-windows-phone-7/">here</a>. To developers like us, it&#8217;s another platform that comes with a whole new gold rush. Why not utilize it?</p>
<p>Recently, I ported one of my app, <a href="http://mugunthkumar.com/iphone/icash-sg/">iCash SG</a> and it&#8217;s now in the 2nd free app in the Navigation Category and is within the top 40 free apps in Singapore MarketPlace.</p>
<p>I&#8217;ll be speaking from those experiences focussing on equivalent techniques between the two operating systems.</p>
<h2>Analogies between the two Operating Systems</h2>
<p>The two operating systems have many things in similar. For example, both support push notifications, both do not support true multi-tasking unlike Android and both of them are highly restricted compared to classical desktop operating systems. As a developer myself, I&#8217;ve tried to de-mystify the different buzzwords used in the Windows Phone forums/blogs and get yourself accustomed with their iOS equivalents.</p>
<h3>UITabbar &lt;==&gt; Panorama/Pivot</h3>
<p>An app that might be using a tab bar controller on iOS will probably be using a <a href="http://msdn.microsoft.com/en-us/library/ff941092(v=VS.92).aspx">Panorama Control</a>. iOS provides a UITabBarController to support displaying views that are <strong>NOT</strong> co-related and a drill-down navigation stack through the UINavigationController for displaying increasingly detailed information. On Windows Phone, you would normally use a panorama control for a UI that would use a UITabBarController.</p>
<p>A panorama is a control with a long horizontal canvas extending beyond the screen bounds. Navigation is supported by a flick gesture. Panorama is recommended for showing views that are <strong>NOT</strong> co-related to each other. For displaying contents that are the same but filtered based on a specific criteria, you must use a <a href="http://msdn.microsoft.com/en-us/library/ff941123(v=VS.92).aspx">Pivot Control</a>.</p>
<p>A good example is the built in Music and Videos hub. When you launch this app, you see a panoramic view that shows the different &#8220;parts&#8221; of the application like radio, history, music, video etc., When you tap on the &#8220;music&#8221; item, your music will be organized based on Artists, Album, Playlists etc, using a Pivot Control. In your application as well, when you are displaying co-related content, use a Pivot Control, otherwise, use a Panorama.</p>
<h3>NavigationController &lt;==&gt; NavigationService</h3>
<p>Lots of differences here. UINavigationController is something that you add into you app. But on Windows Phone, the operating system provides a service called <a href="http://msdn.microsoft.com/en-us/library/system.windows.navigation.navigationservice.aspx">NavigationService</a>. You use this service to navigate between views in your app. In a sophisticated app, you can also use Silverlight&#8217;s powerful Navigation framework class called <a href="http://msdn.microsoft.com/en-us/library/system.windows.navigation.urimapper(VS.92).aspx">UriMapper</a>. While you &#8220;push&#8221; views into a navigation stack on iOS, you &#8220;navigate&#8221; to a page which is addressed using a Uri, just like how you navigate to a page on a website. While on the surface NavigationService looks very easy to use compared to UINavigationController, it&#8217;s not. On Windows Phone 7, you can also navigate out of your app and navigate back in when the user press the back key on the phone. So the design of every page should behave in a &#8220;stateless&#8221; way. While it&#8217;s quite a challenge to design pages like that, If you are depending on information from a previous page, you should cache this when the user navigates out of your page. If this is not done properly, your app might crash when the said page is brought back from, say tombstoned state. Should I say that, such a crash would get your app rejected?</p>
<h3>UITableView &lt;==&gt; ListBox</h3>
<h3><span style="font-weight: normal; font-size: 13px;">Arguably, The most commonly used control on the iOS is a UITableView. The analogous control to this is a ListBox. However, implementation wise, there are quite a lot of difference behind the scenes. You populate a UITableView using delegate methods, while you populate a ListBox by calling adding contents directly into it&#8217;s member Items. A simple code snippet would be</span></h3>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">mainListBox<span style="color: #008000;">.</span><span style="color: #0000FF;">Items</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>myObject<span style="color: #008000;">&#41;</span></pre></div></div>

<p>Note that, this object can be any model object of your class. On the iOS, you &#8220;customize&#8221; the look and feel of the UITableView by customizing each cell with a custom UITableViewCell. On Windows Phone, you do it by a powerful concept called <a href="http://msdn.microsoft.com/en-us/library/cc278072(VS.95).aspx">Data binding</a>. Data binding is ahuge concept in itself, that <a href="http://www.amazon.com/Microsoft-Silverlight-Data-Services-Cookbook/dp/1847199844">separate books are written for that</a>. However, in this post, I&#8217;ll touch upon a few basic concepts on how to display the different entities in the model using this technique.</p>
<h3>Building your Interface</h3>
<p>You can build your interface on Windows Phone using Visual Studio or programmatically in C#. The interface  code is a internally XML based (called XAML) which is again similar to XCode&#8217;s Interface builder&#8217;s XIB files. For better MVC isolation, interface should generally be created using Visual Studio just like how you create Views using Interface Builder. Alternatively, you can also use  Microsoft Expression Blend, which is more matured product than XCode&#8217;s designer, the Interface Builder. Actually, whatever Interface builder can do can be done using Visual Studio, but Microsoft Expression Blend augments what Visual Studio can do to your interface while maintaining compatibility in the generated XAML. In most cases, ExpressionBlend is used to build animation driven user interfaces without writing a single line of code, which is usually done programmatically on iOS using CoreAnimation/QuartzCore framework. So if you were wondering how to do that cool animation you do iOS, look no further, Expression Blend is your friend.</p>
<h3>UITableViewCell &lt;==&gt; Data Templates</h3>
<p>On iOS, the UITableView is usually customized by creating custom UITableViewCell classes. Customized table view cells is arguably the most used step when you write a iOS app. I could even go further and say, if you know to customize a UITableViewCell on the iOS, you already know more than 50% of iOS programming.</p>
<p>On Windows Phone, you do the equivalent by &#8220;applying&#8221; a data template to the listbox to which you added the items. This template is again written in XAML and can either be hand-coded or can be generated using tools like <a href="http://www.microsoft.com/expression">Microsoft Expression Blend</a> The cool idea of using this tool is that Expression Blend tool is a tool designed and made for designers and programmers usually don&#8217;t have to worry about the look and feel of the app.</p>
<p>For better reusability, you can write the data templates as a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.usercontrol(VS.95).aspx">UserControl</a> and use them instead of directly applying an adhoc template to the listbox.</p>
<h3>Isolated Storage &lt;==&gt; NSHomeDirectory()</h3>
<p>On Windows Phone, your app specific files are stored in a sandboxed environment much like the iOS. Microsoft&#8217;s equivalent of this sandbox is called as <a href="http://msdn.microsoft.com/en-us/library/ff626522(v=VS.92).aspx">IsolatedStorage</a>. Files can be read or written only within the confinements of IsolatedStorage.</p>
<p>One thing to remember here is that, IsolatedStorage by default doesn&#8217;t provide you a cache directory like iOS&#8217; NSCachesDirectory. So if your application is going to create large number of cache files, it&#8217;s up to the programmer to create a separate cache folder and empty it at periodic intervals.</p>
<h3>NSUserDefaults &lt;==&gt; IsolatedStorage.ApplicationSettings</h3>
<p>The IsloatedStorage also maintains a LocalSettings file which can be accessed through IsolatedStorage.ApplicationSettings. This is the place where you write your setting related information. Using this is much similar to how you use NSUserDefaults on iOS.</p>
<h3>Push Notifications</h3>
<p>Windows Phone supports four types of notifications.</p>
<p>Toast notifications are notification with alert which are similar to iOS&#8217; notifications with a prompt. However, unlike iOS, users are free to &#8220;ignore&#8221; your toast notification since it&#8217;s not shown as a modal alert.</p>
<p>Tile notifications are notification with a text and badge count to update the tile. This is similar to the badge update on iOS. However, tile notifications are ignored completely by the operating system when the app is not pinned to the home view. So while on the iOS, updating just the badge is a pretty good silent indicator, on Windows Phone it might not.</p>
<p>Raw notifications are  something new to the platform. This notification is used to update your apps&#8217; internal state from your server. Remember that, when your app is not running, this is completely ignored. May be in a later version or so, Windows Phone will allow us to &#8220;wake&#8221; our app from a tomb-stoned state using a raw notification.</p>
<p>A huge and very important diff from iOS is that Microsoft&#8217;s push notification implementation will actually let you know if the notification has been delivered successfully whereas iOS is more like a fire and forget kind.</p>
<h3>Local Notifications &lt;==&gt; TileSchedule</h3>
<p>On iOS , local notifications can do pretty much everything like a push notification. However, on Windows Phone, you can only update the tile image using a &#8220;<a href="http://msdn.microsoft.com/en-us/library/microsoft.phone.shell.shelltileschedule(VS.92).aspx">TileSchedule</a>&#8220;. As on date of writing, even the tile text or the badge count cannot be updated by a TileSchedule. So if you are writing a weather app, be sure to have tile images for every possible weather conditions. Hopefully, Microsoft might come up with more sophisticated features that can be done using this TileSchedule in a subsequent release of the OS.</p>
<h3>How can Microsoft make Windows Phone better for developers</h3>
<p>Realtime information from Camera/Camera overlay view.  This is a very serious omission and as such, Augmented Reality apps cannot be done and apps that do real time video analytics like barcode readers, business card scanners also are impossible.</p>
<p>Not much support for Local notifications. Using a schedule you can only update the tile image but not the tile count or it&#8217;s title.</p>
<p>No proper URL routing support. For example your app cannot handle all &#8220;abc://&#8221; urls like how you do on iOS.</p>
<p>The developer API is not as matured as iOS. With iOS, you can virtually do whatever Apple has done in its apps, which is not the case with Windows Phone. For example, I couldn&#8217;t even figure out how to display the alphabet index like the one you see on the People&#8217;s hub. Microsoft has been a company that doesn&#8217;t release every API or UI element it uses. For example, on Windows 95, you cannot, at least easily with the tools provided back then (VB 4), build a software that looks native like, say, Windows Explorer or the Internet Explorer. The same applies to Windows Phone 7 today. The default tools available from Microsoft doesn&#8217;t allow you to create page animations at least easily. I used this <a href="http://silverlight.codeplex.com/">silverlight-toolkit</a> for page animations and even then it doesn&#8217;t look as native as how Microsoft do it themselves. Being a indie developer on Microsoft platforms is not as easy as it is on Apple. As on date, to create a slick looking UI like, say the built-in mail app, you might need third-party controls like the <a href="http://www.telerik.com/purchase/individual-windows-phone.aspx">telerik</a>, which would set you back by 2000$. Things remain the same as how it was on Windows a decade ago.  Hopefully, Microsoft understands this and opens up their APIs and UI elements. I don&#8217;t think it makes any sense to depend on third party controls for building a product that looks like the native ones. Apple on the other hand helps indie developers by their WWDC sessions, and giving away lots of source code for free.</p>
<p>As such, just like how every application on Windows look different, every app on Windows Phone will look different unlike iOS.</p>
<h3>What Windows Phone has that iOS doesn&#8217;t</h3>
<p>Hubs Integration is a very important and new concept on Windows Phone and some of the apps you write can integrate itself within the built in hubs. For example if you are writing a radio application, it makes more sense to integrate itself into Music and Videos hub than as a standalone app. Similarly, you can integrate your app within the photos hub as photo editors or if you are a content provider for music, you can provide Album art or lyrics right into the Music hub for the currently playing music.</p>
<p>Similarly, I strongly believe that Microsoft will open up People hub integration and so if you make a twitter client, you can sync your twitter information with the People hub. These are some extra things that you must note while developing for Windows Phone as they have no equivalent.</p>
<p>While there are much more to write, and compare, I think, I&#8217;ll write about them in another blog post and hope the post helps in kickstarting with your Windows Phone development.</p>
<p>Do tweet this or share this post if you find it useful.</p>
<p>&#8211;</p>
<p>Mugunth</p>
<p><map name='google_ad_map_961_8b86e81420c6776e'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/961?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_961_8b86e81420c6776e' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=961&amp;url= http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fporting-iphoneios-apps-to-windows-phone%2F' /></p><p><a href ="http://twitter.com/mugunthkumar">Follow me </a> on Twitter</p><p>&copy;2012 <a href="http://blog.mugunthkumar.com">MKBlog</a>. All Rights Reserved.</p>.<h4 id="tweetandlike-heading"></h4><ul id="tweetandlike-buttons"><li><a href="http://twitter.com/share" data-title="Porting+iPhone%2FiOS+apps+to+Windows+Phone" data-count="horizontal" data-text="Porting iPhone/iOS apps to Windows Phone" data-url="http://blog.mugunthkumar.com/articles/porting-iphoneios-apps-to-windows-phone/" data-lang="eng" data-via="@mugunthkumar" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></li><li><g:plusone size= "medium" href= "http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fporting-iphoneios-apps-to-windows-phone%2F"></g:plusone></li><li><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.mugunthkumar.com%2Farticles%2Fporting-iphoneios-apps-to-windows-phone%2F&layout=button_count&show_faces=true&action=like&font=segoe ui&colorscheme=light&width=350&scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:25px;" allowTransparency="true" ></iframe></li></ul>
<p>Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/articles/ui-considerations-mobile-vs-web/' rel='bookmark' title='Designing usable mobile apps'>Designing usable mobile apps</a> <small>Another usability related blog from me after a long time...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.mugunthkumar.com/articles/porting-iphoneios-apps-to-windows-phone/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Introducing MKStoreKit – Version 3</title>
		<link>http://blog.mugunthkumar.com/coding/introducing-mkstorekit-%e2%80%93-version-3/</link>
		<comments>http://blog.mugunthkumar.com/coding/introducing-mkstorekit-%e2%80%93-version-3/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 11:00:50 +0000</pubDate>
		<dc:creator>Mugunth Kumar</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[iphone dev]]></category>
		<category><![CDATA[objective c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[source code]]></category>

		<guid isPermaLink="false">http://blog.mugunthkumar.com/?p=894</guid>
		<description><![CDATA[Update 4: (8th July 2011) MKStoreKit 4.0, an updated version of the one presented here is available. Please check it out and use 4.0 instead of this. Around last year this time, I wrote a singleton class, MKStoreKit, and a blog post, wrapping Apple&#8217;s StoreKit framework and it has been quite popular. From the email [...]
Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/' rel='bookmark' title='MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions'>MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions</a> <small>MKStoreKit started off in a pet project a couple of...</small></li>
<li><a href='http://blog.mugunthkumar.com/coding/using-mkstorekit-in-your-apps/' rel='bookmark' title='Using MKStoreKit in your apps'>Using MKStoreKit in your apps</a> <small>MKStoreKit, as you probably know is a framework for implementing...</small></li>
<li><a href='http://blog.mugunthkumar.com/coding/in-app-purchases-troubleshooting-code0-cannot-connect-to-itunes-store-skerrorunknown/' rel='bookmark' title='In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)'>In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)</a> <small>When using MKStoreKit or any other equivalent framework or regular...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p><strong>Update 4: (8th July 2011) <a href="http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/">MKStoreKit 4.0</a>, an updated version of the one presented here is available. Please check it out and use 4.0 instead of this.<br />
</strong><br />
Around last year this time, I wrote a singleton class, MKStoreKit, <a href="http://blog.mugunthkumar.com/coding/iphone-tutorial-–-in-app-purchases/">and a blog post</a>, wrapping Apple&#8217;s StoreKit framework and it has been quite popular. From the email responses I receive, I could say, it&#8217;s been in use in more than thousands of apps on the AppStore. It has been very successful toolkit that, it was referred as the &#8220;goto&#8221; toolkit for in-app purchases.</p>
<div id="attachment_948" class="wp-caption aligncenter" style="width: 310px"><a href="http://blog.mugunthkumar.com/wp-content/uploads/MKStoreKit.png"><img class="size-medium wp-image-948" title="MKStoreKit" src="http://blog.mugunthkumar.com/wp-content/uploads/MKStoreKit-300x46.png" alt="" width="300" height="46" /></a><p class="wp-caption-text">A WordPress Statistics showing that MKStoreKit is a more popular keyword for Search</p></div>
<p style="text-align: center;">&nbsp;</p>
<p>Developers even search for MKStoreKit (might be they heard it through word-of-mouth). Now, I think, it&#8217;s time to re-write it from the scratch. Since MKStoreKit is quite successful, I think it&#8217;s time to introduce some &#8220;standards&#8221; into the framework.</p>
<h2>What&#8217;s new in 3.0</h2>
<p>MKStoreKit 3.0 adds support for product availability notifications, cancelled transaction notification, restore transactions, server product model support, super easy consumable support and built in ability to display product titles along with their localized price. We will look at them one by one in this post.</p>
<h3>Products available notification</h3>
<p>MKStoreKit 3.0 can notify the delegate handler when Apple&#8217;s storekit framework returns</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>productFetchComplete;
<span style="color: #11740a; font-style: italic;">// variable that tracks the state of StoreManager's product availability</span>
<span style="color: #a61390;">BOOL</span> isProductsAvailable;</pre></div></div>

<p>Handle this delegate and refresh your views that shows your list of in-app products. There is also a variable called isProductsAvailable. If this is false, you can show a spinner till you get the productFetchComplete delegate returns. If it&#8217;s &#8220;YES&#8221;, you can call necessary functions.to display your products. MKStoreKit 3.0 has another function to format the product name with their localized name, description and currency.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSMutableArray</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> purchasableObjectsDescription;</pre></div></div>

<p>When you call [[MKStoreManager sharedManager] purchaseableObjectsDescription] you wil get a array of strings which you can straight away use it for displaying on your table view. With little tweaks to that method, you can customize it to display however you want. Note that this returned array will be empty when isProductsAvailable is &#8220;NO&#8221;</p>
<h3>Restore transactions with ease</h3>
<p>First and foremost request was for adding the ability to restore purchases.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> restorePreviousTransactions;</pre></div></div>

<p>Just call [[MKStoreManager sharedManager] restorePreviousTransactions] from your IBAction for the restore button.</p>
<h3>Super easy consumable support</h3>
<p>The new version of MKStoreKit has a very easy and slick support for Consumables. It automatically keeps track of the quantity of the consumable quantity and you can use helper methods within MKStoreKit to check if the user has enough quantity of the consumable for use.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span> canConsumeProduct<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> productIdentifier quantity<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span> quantity;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span> consumeProduct<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> productIdentifier quantity<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span> quantity;</pre></div></div>

<p>Now you don&#8217;t get all these features for free. You need to customize MKStoreKit by telling which of your product is a consumable and which one is a non-consumable. And for each consumable product id, you must configure it to tell MKStoreKit the actual virtual count associated with it.</p>
<p>For example, you might have a &#8220;Fish Tank&#8221; where users can buy &#8220;eggs&#8221;. You have a &#8220;small&#8221; basket, &#8220;medium&#8221; basket. You need to tell MKStoreKit, how many &#8220;eggs&#8221; each consumable contain so that you can use the built in helper methods to consume them and to check if the user has &#8220;enough&#8221; items to consume. While it all looks complicated outside, I have introduced some naming convention standards that makes life easy here.</p>
<blockquote><p>Naming a product identifier with a trailing number tells MKStoreKit to treat it as a consumable.</p></blockquote>
<p>So in this fish tank case, you can have<br />
com.mycompany.myfishtankapp.fish1 as a non-consumable and<br />
com.mycompany.myfishtankapp.eggs.small.5 as a consumable that gives &#8220;5&#8243; eggs to the user to consume.</p>
<p>If you follow this simple naming convention when you create your consumables, it will be super easy to use with MKStoreKit 3.0</p>
<h3>Support for cancelled transaction delegate</h3>
<p>The next big request was to add support for cancelled transactions. The time it takes for Apple&#8217;s storekit framework to show the In-App purchase prompt. While developers show a simple spinner, it wasn&#8217;t possible to stop or hide the spinner when the user cancels the transaction. MKStoreKit 3.0 adds a new delegate method that notifies you of a cancelled transaction.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>transactionCanceled;
<span style="color: #11740a; font-style: italic;">// as a matter of UX, don't show a &quot;User Canceled transaction&quot; alert view here</span>
<span style="color: #11740a; font-style: italic;">// use this only to &quot;enable/disable your UI or hide your activity indicator view etc.,</span></pre></div></div>

<h3>Support for server product model</h3>
<p>The new and improved MKStoreKit 3.0 also supports Server Product Model and improved support for consumables. Configuring your server for server product model is super easy with the PHP scripts bundled with MKStoreKit. Just change the SERVER_PRODUCT_MODEL macro to 1 and MKStoreKit will ping your servers for receipt verification. What&#8217;s more? The PHP code for verifying receipts is also bundled with MKStoreKit 3.0.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#define SERVER_PRODUCT_MODEL 0</span></pre></div></div>

<h2>Links to my old posts</h2>
<ol>
<li><a href="http://blog.mugunthkumar.com/coding/iphone-tutorial-%e2%80%93-in-app-purchases/">iPhone Tutorial – In-App Purchases</a></li>
<li><a href="http://blog.mugunthkumar.com/coding/iphone-tutorial-enabling-reviewers-to-use-your-in-app-purchases-for-free/">iPhone Tutorial &#8211; Enabling reviewers to use your In-App purchases for free</a></li>
</ol>
<p>As a matter of fact, the source code links on the old posts will be removed 1 month from the today and MKStoreKit 3.0 will be the only supported version (if everything goes well). In case you need the old code, you can drop me an email, but it will not be supported.</p>
<h2>Source code</h2>
<p><del>The source code for MKStoreKit 3.1 is attached here.</del><br />
<del> <a href="http://blog.mugunthkumar.com/wp-content/uploads/MKStoreKit-v3.1.zip">MKStoreKit v3.1</a></del><br />
<strong>Update 3: (8th July 2011) <a href="http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/">MKStoreKit 4.0</a>, an updated version of the one presented here is available. Please check it out and use 4.0 instead of this.</strong><br />
<strong>Update 2 (4th Dec 2010)</strong>: MKStoreKit will not initialize and use up memory when you run from simulator.<br />
<strong>Update 1 (24th Nov 2010)</strong>: Minor compilation bug kFeatureBId missing fixed. Please download latest files again.</p>
<h2>Support me</h2>
<p>Hourly rates of a iPhone developer is <a href="http://stackoverflow.com/questions/209170/how-much-does-it-cost-to-develop-an-iphone-application">skyrocket high</a>. I believe this code would have saved your coding hours by at least a day. You can consider supporting further development by funding me through <a href="https://www.paypal.com">PayPal</a>.  My PayPal email is mugunth.kumar@gmail.com</p>
<p><map name='google_ad_map_894_8b86e81420c6776e'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/894?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_894_8b86e81420c6776e' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=894&amp;url= http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fintroducing-mkstorekit-%25e2%2580%2593-version-3%2F' /></p><p><a href ="http://twitter.com/mugunthkumar">Follow me </a> on Twitter</p><p>&copy;2012 <a href="http://blog.mugunthkumar.com">MKBlog</a>. All Rights Reserved.</p>.<h4 id="tweetandlike-heading"></h4><ul id="tweetandlike-buttons"><li><a href="http://twitter.com/share" data-title="Introducing+MKStoreKit+%E2%80%93+Version+3" data-count="horizontal" data-text="Introducing MKStoreKit – Version 3" data-url="http://blog.mugunthkumar.com/coding/introducing-mkstorekit-%e2%80%93-version-3/" data-lang="eng" data-via="@mugunthkumar" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></li><li><g:plusone size= "medium" href= "http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fintroducing-mkstorekit-%25e2%2580%2593-version-3%2F"></g:plusone></li><li><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fblog.mugunthkumar.com%2Fcoding%2Fintroducing-mkstorekit-%25e2%2580%2593-version-3%2F&layout=button_count&show_faces=true&action=like&font=segoe ui&colorscheme=light&width=350&scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:25px;" allowTransparency="true" ></iframe></li></ul>
<p>Related posts:<ol>
<li><a href='http://blog.mugunthkumar.com/coding/mkstorekit-4-0-supporting-auto-renewable-subscriptions/' rel='bookmark' title='MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions'>MKStoreKit 4.0 &#8211; Supporting Auto Renewable Subscriptions</a> <small>MKStoreKit started off in a pet project a couple of...</small></li>
<li><a href='http://blog.mugunthkumar.com/coding/using-mkstorekit-in-your-apps/' rel='bookmark' title='Using MKStoreKit in your apps'>Using MKStoreKit in your apps</a> <small>MKStoreKit, as you probably know is a framework for implementing...</small></li>
<li><a href='http://blog.mugunthkumar.com/coding/in-app-purchases-troubleshooting-code0-cannot-connect-to-itunes-store-skerrorunknown/' rel='bookmark' title='In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)'>In App Purchases: Troubleshooting Code=0 &#8220;Cannot connect to iTunes Store&#8221; (SKErrorUnknown)</a> <small>When using MKStoreKit or any other equivalent framework or regular...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.mugunthkumar.com/coding/introducing-mkstorekit-%e2%80%93-version-3/feed/</wfw:commentRss>
		<slash:comments>99</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: blog.mugunthkumar.com @ 2012-02-04 14:22:09 -->
