<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Jayway Team Blog » Cocoa</title>
	
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Thu, 01 Apr 2010 08:41:54 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/jayway/posts/cocoa" /><feedburner:info uri="jayway/posts/cocoa" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:browserFriendly></feedburner:browserFriendly><item>
		<title>Performing any Selector on the Main Thread</title>
		<link>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/</link>
		<comments>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 14:57:48 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[cocoa touch]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5209</guid>
		<description><![CDATA[Many UI frameworks, including AppKit for Mac OS X and UIKit for iPhone OS, require that all methods to UI components are sent on the main UI thread. Cocoa and Cocoa Touch make this quite easy by providing for example -[NSObject performSelectorOnMainThread:withObject:waitUntilDone:] in Foundation. Making updating the text for a text field a snap:
[someTextField performSelectorOnMainThread:@selector(setText:)
 [...]]]></description>
			<content:encoded><![CDATA[<p>Many UI frameworks, including AppKit for Mac OS X and UIKit for iPhone OS, require that all methods to UI components are sent on the main UI thread. Cocoa and Cocoa Touch make this quite easy by providing for example <code>-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]</code> in Foundation. Making updating the text for a text field a snap:</p>
<pre class="brush:objc">[someTextField performSelectorOnMainThread:@selector(setText:)
                              	withObject:@"A new text"
                             waitUntilDone:YES];</pre>
<h3>But not everything is an object</h3>
<p>Since Objective-C is a superset of C, there are still all the types from C available. Such as all the primitives, including enums, and more complex struct types. Cocoa Touch is pragmatic and will use the most proper type for the use-case, not forcing everything into a square OOP hole.</p>
<p>This makes it quite hard to call for example <code>-[UIView setHidden:]</code>, that takes a single <code>BOOL</code> argument. Same for <code>-[UIView setFrame:]</code>, that takes a single <code>CGRect</code> struct argument, that in turn consists of one <code>CGPoint</code> and one <code>CGSize</code> struct.</p>
<p>Every type imaginable in C can be bundled in an <code>NSValue</code> instance. So we could bundle up the <code>BOOL</code> primitive, or the <code>CGRect</code> struct in a <code>NSValue</code> object. Then pass that object to the main thread, where it is unbundled and passed to the desired method. Quite cumbersome as it requires us to bundle, and unbundle types manually, and implement at least one extra method.</p>
<h3>There must be an easier way</h3>
<p>It turns out that <code>NSInvocation</code> can also handle any imaginable C type, or else it would not be able to invoke any imaginable Objective-C method. Making a <code>NSInvocation</code> invoke its method on the main thread is easy enough. Just add a category to the <code>NSInvocation</code> class, with a new method like this:</p>
<pre class="brush:objc">-(void)invokeOnMainThreadWaitUntilDone:(BOOL)wait;
{
  [self performSelectorOnMainThread:@selector(invoke)
                         withObject:nil
                      waitUntilDone:wait];
}</pre>
<p>So now all you need to do is to create a <code>NSInvocation</code> object, fill it in with the primitive or struct types, and invoke it on the main thread. But creating and setting up a <code>NSInvocation</code> object is also a bit on the boring side...</p>
<h3>There must be an even easier way!</h3>
<p>We could use variable argument lists from plain old C. Too bad that they are untyped?<br />
No despair, we know the target object for our invocation, and we know what method to call. So we have what we need to fetch the <code>NSMethodSignature</code> object for the call, that contains all the type information we need to safely process the <code>va_list</code>.</p>
<p>Our target machine is a Mac running 32- or 64-bit Intel CPU, or an iPhone OS device with a 32 bit ARM CPU. Turns out that on both platforms <code>va_list</code> is simply a <code>void*</code> pointer, to the stack frame. Even better <code>va_start()</code> will always flush any argument passed into the register on the stack frame. So we can skip most of the boring argument handling, by treating the arguments like a byte buffer, only advancing and aligning the buffer according to the information in the <code>NSMethodSignature</code> object.</p>
<p>A convenience method for creating a <code>NSInvocation</code> object for a particular target, selector, and list of variable arguments, would turn out like this:</p>
<pre class="brush:objc">+(NSInvocation*)invocationWithTarget:(id)target
                            selector:(SEL)aSelector
                     retainArguments:(BOOL)retainArguments, ...;
{
  va_list ap;
  va_start(ap, retainArguments);
  char* args = (char*)ap;
  NSMethodSignature* signature = [target methodSignatureForSelector:aSelector];
  NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
  if (retainArguments) {
    [invocation retainArguments];
  }
  [invocation setTarget:target];
  [invocation setSelector:aSelector];
  for (int index = 2; index < [signature numberOfArguments]; index++) {
    const char *type = [signature getArgumentTypeAtIndex:index];
    NSUInteger size, align;
    NSGetSizeAndAlignment(type, &size, &align);
    NSUInteger mod = (NSUInteger)args % align;
    if (mod != 0) {
      args += (align - mod);
    }
    [invocation setArgument:args atIndex:index];
    args += size;
  }
  va_end(ap);
  return invocation;
}
</pre>
<h3>Conclusion</h3>
<p>And now we can easily call any method on the main UI thread. </p>
<p>An example where a <code>CGRect</code> struct is used to update the UI components frame;</p>
<pre class="brush:objc">// Set new frame of a label.
[[NSInvocation invocationWithTarget:someLabel
                           selector:@selector(setFrame:)
                    retainArguments:NO, CGRectMake(40, 40, 200, 100)]
 invokeOnMainThreadWaitUntilDone:NO];</pre>
<p>A slightly more complex example, where we send a primitive int, and also waits for and fetches the result from the main thread:</p>
<pre class="brush:objc">// Query a UITableView for the number of rows in section 2.
NSInvocation* i = [NSInvocation invocationWithTarget:tableView
                                            selector:@selector(numberOfRowsInSection:)
                                     retainArguments:NO, (NSUInteger)2];
// Block this thread until method has been invoked and result is available.
[i invokeOnMainThreadWaitUntilDone:YES];
NSInteger numberOfRows;
[i getReturnValue:&numberOfRows];</pre>
<p>Download full source code here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/03/NSInvocation+CWVariableArguments.zip'>NSInvocation+CWVariableArguments.zip</a></p>
<p><em>Update: Example 2 was not 64-bit compatible as <a href="http://twitter.com/chmod007">David Remahl</a> pointed out to me. Added type cast to fix the error.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>iPad, the Future, and the Luxury of Starting Over</title>
		<link>http://blog.jayway.com/2010/01/28/ipad-the-future-and-the-luxury-of-starting-over/</link>
		<comments>http://blog.jayway.com/2010/01/28/ipad-the-future-and-the-luxury-of-starting-over/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 20:02:59 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[cocoa touch]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[innovation]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[iphone]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4550</guid>
		<description><![CDATA[A luxury that you seldom have in the world of software development is the luxury of starting over. I am not talking about throwing away everything and start from scratch. But just taking what you have, and all the experiences learned. Apply some major refactoring to make what works really shine, and without care of [...]]]></description>
			<content:encoded><![CDATA[<p>A luxury that you seldom have in the world of software development is the luxury of starting over. I am not talking about throwing away everything and start from scratch. But just taking what you have, and all the experiences learned. Apply some major refactoring to make what works really shine, and without care of dependent clients throw out everything that turned out to be irreparable.</p>
<p>The <a href="http://www.apple.com/ipad/">iPad</a> as presented by Apple on the <a href="http://www.apple.com/ipad/">special january 2010 event</a> is a showcase of how Apple has been given this luxury. Not just once but over and over again. Allowing for iterating, and improving with each restart.</p>
<h3>The origins</h3>
<p>The evolution of the software running the iPad can be traced back along with <a href="http://en.wikipedia.org/wiki/Steve_Jobs">Steve Jobs</a> himself. With the first <a href="http://en.wikipedia.org/wiki/Macintosh">Macintosh</a> from 1984 he was one of the many talented people behind ushering the graphical user interface into the world of normal people. </p>
<p>Not entirely by his own choice he founded <a href="http://en.wikipedia.org/wiki/NeXT">NeXT</a> in 1985, and got the luxury of starting over, equipped with the experience from the Macintosh project. The lessons learned resulted in the NeXT computers in 1989, a system way ahead of it's time, with <a href="http://en.wikipedia.org/wiki/NeXTSTEP">NextStep's</a> object oriented frameworks, before OOP had even caught on with the main stream. Remember this was before <a href="http://en.wikipedia.org/wiki/Windows_3.0">Windows 3.0</a>.</p>
<p>In late 1996 Apple bought NeXT and all their assets, including Steve Jobs as the CEO. Now the experience learned from developing the NeXT computers and the NextStep operating system could be used again. With the luxury of a reset once again, throwing out anything that did not work, and clean up the parts that worked well. The new operating system rising from the ashes would be named <a href="http://en.wikipedia.org/wiki/Mac_OS_X">Mac OS X</a>, and the application development frameworks be called <a href="http://developer.apple.com/cocoa/">Cocoa</a>.</p>
<h3>The tech as used today</h3>
<p>Cocoa is the primary application development framework for Mac OS X to this day. It is an umbrella framework, containing:</p>
<ul>
<li><a href="http://developer.apple.com/mac/library/navigation/index.html#section=Frameworks&topic=Foundation">Foundation</a> - For the non-visual low level components.</li>
<li><a href="http://developer.apple.com/mac/library/navigation/index.html#section=Frameworks&topic=Application%20Kit">AppKit</a> - For the components to create a desktop application with mouse and keyboard</li>
<li><a href="http://developer.apple.com/mac/library/navigation/index.html#section=Frameworks&topic=Core%20Data">Core Data</a> - For managing application data as a graph database.</li>
</ul>
<p>The application development framework for <a href="http://en.wikipedia.org/wiki/IPhone_OS">iPhone OS</a> is called <a href="http://developer.apple.com/iphone/library/navigation/index.html#section=Frameworks&topic=Cocoa%20Touch%20Layer">Cocoa Touch</a>. It is basically all the nice parts from Foundation, and since iPhone OS 3.0 also Core Data. But AppKit is missing, instead replaced by <a href="http://developer.apple.com/iphone/library/navigation/index.html#section=Frameworks&topic=UIKit">UIKit</a>. UIKit are the components needed to create a graphical user interface based on multitouch. Not a dumbed down version of AppKit, but a rewrite that is re-using the experience from AppKit. Refining what works well, removing what did not turn out so well, and adding what could not easily be added to AppKit.</p>
<p>Apple gave themselves the luxury of starting over yet again, not burdened by backward compaitibility. The new form factor of the iPhone can not inspire any realistic hopes for application compatibility with the Mac computers. </p>
<h3>Where can this lead?</h3>
<p>Mac OS X and the Cocoa frameworks where good from a tech standpoint, and for us nerds. But not ready for prime-time by the average user until at least version 10.2, or 10.3 if you are really honest. Many dismissed the first versions of Mac OS X, while others saw the potential. I see the same thing with iPad and iPhone OS, it will be dismissed for now, and others will see a great potential.</p>
<p>I think that the iPad is Apple's vision for the future of computing. Mice to be replaced by multi-touch. The keyword being <strong>multi</strong>-touch. A touch device is to a multi-touch device what a black and white TV is to a modern color HD TV. Sure they both display pictures, the basic idea is there, but the execution is on a different level. In 1984 with the first Macintosh a computer mouse was a novelty. Apple want to replace the secondary input of the mouse, with direct input and manipulation using your very fingers. Making the mouse computer mouse a parenthesis in the history of computing.</p>
<p><strong>The iPhone OS is the successor to Mac OS X.</strong></p>
<p>There I said it. There will never be a Mac OX X 11.0, and probably not a Mac OS X 10.8 either. That line of succession is over, the new blood line to reign is the offspring that is iPhone OS. A fresh start, a luxury in our industry, and also a necessity in order to take the great leaps to the future.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/28/ipad-the-future-and-the-luxury-of-starting-over/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Google Translate and iPhone apps</title>
		<link>http://blog.jayway.com/2010/01/11/google-translate-and-iphone-apps/</link>
		<comments>http://blog.jayway.com/2010/01/11/google-translate-and-iphone-apps/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 09:22:17 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[localization]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4251</guid>
		<description><![CDATA[The Cocoa and Cocoa Touch frameworks has a really nice function for acquiring a localized string NSLocalizedString(). Just pass in a key and you are done, for strings that are known at least. Sometimes you are getting unknown strings from a data source not under your control, strings representing just a fraction of the text [...]]]></description>
			<content:encoded><![CDATA[<p>The Cocoa and Cocoa Touch frameworks has a really nice function for acquiring a localized string <code>NSLocalizedString()</code>. Just pass in a key and you are done, for strings that are known at least. Sometimes you are getting unknown strings from a data source not under your control, strings representing just a fraction of the text in your UI. Leaving this text in it's source language looks weird, and skipping translation all together just feel wrong.</p>
<h3>Google Translate to the rescue</h3>
<p>Turns out that Google Translate has a nice AJAX API, feed it a URL request and get a JSON response. Admittedly the translations are not always perfect, even quite humorous at times, but good enough if you provide the user a warning.</p>
<p>So let us create a sibling to <code>NSLocalizedString()</code> called <code>CWTranslatedString()</code>. It should take two arguments; the string to translate, and the source language ISO code. We should also be able to get the users currently selected language, that will be used as the destination language when translating. So this is our header:</p>
<pre class="brush:c">NSString* CWCurrentLanguageIdentifier();
NSString* CWTranslatedString(NSString* string, NSString* sourceLanguageIdentifier);</pre>
<p>Currently your iPhone application must be terminated in order for the user to change the language. And even when Apple adds multitasking for third-party apps we can assume the user do not go about and switch languages too often, so we let <code>CWCurrentLanguageIdentifier()</code> cache the language code:</p>
<pre class="brush:c">NSString* CWCurrentLanguageIdentifier() {
    static NSString* currentLanguage = nil;
    if (currentLanguage == nil) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSArray* languages = [defaults objectForKey:@"AppleLanguages"];
        currentLanguage = [[languages objectAtIndex:0] retain];
    }
    return currentLanguage;
}</pre>
<p>Now for the <code>CWTranslatedString()</code> function. The JSON response from Google Translate is well formatted with no line breaks, so let's not bother with a proper JSON-parser. We can use a simple <code>NSScanner</code>, and just return the source string for any unexpected result. We also short circuit and return the source string if the source and dest language as equal.</p>
<pre class="brush:c">NSString* CWTranslatedString(NSString* string, NSString* sourceLanguageIdentifier) {
    static NSString* queryURL = @"http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%@&langpair=%@%%7C%@";
    if (sourceLanguageIdentifier == nil) {
        sourceLanguageIdentifier = @"en";
    }
    if ([sourceLanguageIdentifier isEqual:CWCurrentLanguageIdentifier()] || string == nil) {
        return string;
    }
    NSString* escapedString = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString* query = [NSString stringWithFormat:queryURL,
                       escapedString, sourceLanguageIdentifier, CWCurrentLanguageIdentifier()];
    NSString* response = [NSString stringWithContentsOfURL:[NSURL URLWithString:query]
                                                  encoding:NSUTF8StringEncoding error:NULL];
    if (response == nil) {
        return string;
    }
    NSScanner* scanner = [NSScanner scannerWithString:response];
    if (![scanner scanUpToString:@"\"translatedText\":\"" intoString:NULL]) {
        return string;
    }
    if (![scanner scanString:@"\"translatedText\":\"" intoString:NULL]) {
        return string;
    }
    NSString* result = nil;
    if (![scanner scanUpToString:@"\"}" intoString:&result]) {
        return string;
    }
    return result;
}</pre>
<p>And that is it. Not perfect, but nice to have.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/11/google-translate-and-iphone-apps/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Add some polish to iPhone app start up</title>
		<link>http://blog.jayway.com/2009/06/29/add-some-polish-to-iphone-app-start-up/</link>
		<comments>http://blog.jayway.com/2009/06/29/add-some-polish-to-iphone-app-start-up/#comments</comments>
		<pubDate>Mon, 29 Jun 2009 07:13:06 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1885</guid>
		<description><![CDATA[First impressions last, and the very first impression your users have of your iPhone application is the start up. First step is to have a nice Default.png, but not many words spilled on that one, it is well covered in Apple's documentation.
Creating a perfect Default.png is impossible, especially if you have different setup of navigation [...]]]></description>
			<content:encoded><![CDATA[<p>First impressions last, and the very first impression your users have of your iPhone application is the start up. First step is to have a nice <code>Default.png</code>, but not many words spilled on that one, it is well covered in Apple's documentation.</p>
<p>Creating a perfect <code>Default.png</code> is impossible, especially if you have different setup of navigation and tab bars in different parts of your app. And even harder to adjust for the different sizes of the status bar. With the advent of tethering the size of the status bar is even more sure to be random at startup. This adds to a small jerk, or ugly jump of the user interface at start up.</p>
<h3>Create a smooth startup</h3>
<p>The easiest way to counter this small jerk is to let your user interface fade in. It is pleasing to the eye, and easy to do. So easy that this blog post pretty much ends after a small code block you can cut&paste into any of your projects.</p>
<p>If you create your UI using Interface Builder, or create it in code, you still have an implementation of <code>applicationDidFinishLaunching:</code> that ends like this:</p>
<pre class="objc">-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>applicationDidFinishLaunching:<span style="color: #002200;">&#40;</span>UIApplication*<span style="color: #002200;">&#41;</span>application;
<span style="color: #002200;">&#123;</span>
<span style="color: #ff0000;">// ...more code...</span>
  <span style="color: #002200;">&#91;</span>window makeKeyAndVisible<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>This is where we will add our own code that will slide in a new view, above the root view, mimicking the <code>Default.png</code> look. This view is then quickly faded out and removed, creating the appearance of fading in our real user interface.</p>
<pre class="objc">-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>applicationDidFinishLaunching:<span style="color: #002200;">&#40;</span>UIApplication*<span style="color: #002200;">&#41;</span>application;
<span style="color: #002200;">&#123;</span>
<span style="color: #ff0000;">// ...more code...</span>
  UIImage* backImage = <span style="color: #002200;">&#91;</span>UIImage imageNamed:@<span style="color: #666666;">&quot;Default.png&quot;</span><span style="color: #002200;">&#93;</span>;
  UIView* backView = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIImageView alloc<span style="color: #002200;">&#93;</span> initWithImage:backImage<span style="color: #002200;">&#93;</span>;
  backView.frame = window.bounds;
  <span style="color: #002200;">&#91;</span>window addSubview:backView<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>UIView beginAnimations:@<span style="color: #666666;">&quot;CWFadeIn&quot;</span> context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>backView<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>UIView setAnimationDelegate:self<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>UIView setAnimationDidStopSelector:
      <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>animationDidStop:finished:context:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>UIView setAnimationDuration:<span style="color: #0000dd;">0</span>.5f<span style="color: #002200;">&#93;</span>;
  backView.alpha = <span style="color: #0000dd;">0</span>;
  <span style="color: #002200;">&#91;</span>UIView commitAnimations<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>window makeKeyAndVisible<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>animationDidStop:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>*<span style="color: #002200;">&#41;</span>animationID finished:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSNumber.html"><span style="color: #0000ff;">NSNumber</span></a>*<span style="color: #002200;">&#41;</span>finished
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context
<span style="color: #002200;">&#123;</span>
  UIView* backView = <span style="color: #002200;">&#40;</span>UIView*<span style="color: #002200;">&#41;</span>context;
  <span style="color: #002200;">&#91;</span>backView removeFromSuperview<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>backView release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>And that is it, instant better first impression.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/06/29/add-some-polish-to-iphone-app-start-up/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Regular Expressions and Cocoa</title>
		<link>http://blog.jayway.com/2009/05/06/regular-expressions-and-cocoa/</link>
		<comments>http://blog.jayway.com/2009/05/06/regular-expressions-and-cocoa/#comments</comments>
		<pubDate>Wed, 06 May 2009 19:36:27 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[regex]]></category>

		<guid isPermaLink="false">http://79.125.9.149/?p=1617</guid>
		<description><![CDATA[Regular expressions is a powerful tool for solving many problems related to text. It can be misused as any good tool, but there are moments when they are the best solution for a given problem. At those moments the lack of regular expressions for Cocoa on Mac OS X and Cocoa Touch on iPhone OS [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Regular_expression">Regular expressions</a> is a powerful tool for solving many problems related to text. It can be misused as any good tool, but there are moments when they are the best solution for a given problem. At those moments the lack of regular expressions for Cocoa on Mac OS X and Cocoa Touch on iPhone OS is a pain in the butt.</p>
<p>Or are regular expressions really missing? Regular expressions can be used with <code>NSPredicate</code> that is part of Core Data, available since Mac OS X 10.4 and officially announced for iPhone OS 3.0. Cocoa's <code>WebView</code> and the equivalent <code>UIWebView</code> in Cocoa Touch both support JavaScript with regular expressions. So there sure is regular expressions available on the platforms, but how do you make it available for your own code?</p>
<h3>An Ugly Solution</h3>
<p>You can actually get access to the regular expression engine through JavaScript, unfortunately this requires a roundtrip through <a href="http://webkit.org/">WebKit</a>. On an iPhone this means you have to use an off-screen instance of <code>UIWebView</code>, and delegate execution of regular expression to it. </p>
<p>The complexity of an off-screen <code>WebView</code> or <code>UIWebView</code> could be hidden by a utility class. But the extra glue code needed to make something useful out of the single method <code>stringByEvaluatingJavaScripFromString:</code>, would be allot.</p>
<h3>What Apple Recommends</h3>
<p>For most problems the official stance is correct; do not use regular expressions. Instead use <code>NSScanner</code>, that is perfect for sequentially parse texts. It is very fast and can substitute any regular expressions that only relies on:
<ul>
<li>Character sets</li>
<li>Exact string matches</li>
<li>Numerical matches</li>
<li>Uniform input text</li>
</ul>
<p>These conditions hold true to 95% of everything regular expressions is ever used for. For the other 5%, Apple leaves you to fend for your own.</p>
<h3>Other Solutions</h3>
<p><a href="http://www.pcre.org/">PCRE</a> compiles perfectly with Cocoa, since it is written in C, one of the many advantages of Objective-C. PCRE is very capable, and almost a standard, but also very large. For an iPhone application the PCRE implementation could end up as the majority of your executables file-size. If this is something you can live with, then the open source <a href="http://regexkit.sourceforge.net/">RegexKit</a> framework wraps PCRE in Cocoa and Cocoa Touch friendly Objective-C.</p>
<p>Another regular expressions framework is <a href="http://www8.ocn.ne.jp/~sonoisa/OgreKit/">OgreKit</a>. The advantage of OgreKit is full unicode support, with the same disadvantage of size. And the fact that the documentation is in Japanese.</p>
<h3>A Pretty Solution</h3>
<p>It turns out that Mac OS X for years, and iPhone OS since inception, has been shipped with a perfectly good regular expressions engine. This engine is based on the <a href="http://site.icu-project.org/">ICU specification</a>, so it works perfectly with unicode and is well on par with PCRE for functionality. This framework is simply called ICU Core, and has a C interface. But for a Cocoa programmers the C interface is not nice enough, and thankfully <a href="http://twitter.com/johnengelhart">John Engelhart</a> has done this work for us, with <a href="http://regexkit.sourceforge.net/RegexKitLite/">RegexKitLite</a>. RegexKitLite is a little brother to RegexKit that wrapps ICU Core instead of PCRE.</p>
<p>RegexKitLite is published under <a href="http://en.wikipedia.org/wiki/BSD_license">BSD license</a>, and is simply two files you add to your project, fully compatible with all available versions of both Mac OS X and iPhone OS. The tricky part is that ICU Core is not a public API officially supported by Apple, even though it has existed unchanged for years. Good news is that using ICU Core is not a show stopper for publishing on the iPhone App Store, application out there already uses it, both <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=284540316&mt=8">well known</a> and <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=305963116&mt=8">not so well known</a>.</p>
<h3>Setting Up RegexKitLite</h3>
<ol>
<li>Download the latest version from the <a href="http://sourceforge.net/project/showfiles.php?group_id=204582&package_id=268643">sourceforge webpage</a>, or <a href="http://sourceforge.net/scm/?type=svn&group_id=204582">SVN</a>.</li>
<li>Add <code>RegexKitLite.h</code> and <code>RegexKitLite.m</code> to your project.</li>
<li>Link your project against ICU Core, by adding the linker flag <code>-licucore</code> to <em>Other Linker Flags</em> under your projects build settings.</li>
</ol>
<p>Optionally you can also add the documentation to Xcode with these easy steps:</p>
<ol>
<li>Open <em>Help -> Documtantion</em>.</li>
<li>Press the Gears button in the lower left corder, and select <em>New Subscription...</em>.</li>
<li>Enter <code>feed://regexkit.sourceforge.net/RegexKitLiteDocSets.atom</code> as URL.</li>
</ol>
<h3>Using RegexKitLite</h3>
<p>This post is not a tutorial on regular expressions, but a tutorial on a partical API for executing regular expressions. If you want to learn more about regular expressions themselves I would recomend you look at <a href="http://www.regular-expressions.info">Regular Expressions.info</a>.</p>
<p>RegexKitLite provides it's functionality as categories on <code>NSString</code> and <code>NSMutableString</code>. This way using regular expressions with Cocoa is just as easy and normal string manipulation. This is best described using examples.</p>
<p>A simple example that normalizes a text with single white spaces, kind of like how a HML renderer would do, so this is handy when scraping web pages:</p>
<pre class="objc"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* source = @<span style="color: #666666;">&quot;One<span style="color: #666666; font-weight: bold;">\t</span> Two <span style="color: #666666; font-weight: bold;">\n</span>Three &quot;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* result = <span style="color: #002200;">&#91;</span>source stringByReplacingOccurancesOfRegex:@<span style="color: #666666;">&quot;<span style="color: #666666; font-weight: bold;">\\</span>s+&quot;</span>
    withString:@<span style="color: #666666;">&quot; &quot;</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span>source<span style="color: #002200;">&#41;</span>;
NSLog<span style="color: #002200;">&#40;</span>result<span style="color: #002200;">&#41;</span>;</pre>
<p>Or you can split a text, such as semi-colon delimeted data:</p>
<pre class="objc"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* source = @<span style="color: #666666;">&quot;Test;12;Y&quot;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>* columns = <span style="color: #002200;">&#91;</span>source componentsSeparatedByRegex:@<span style="color: #666666;">&quot;;<span style="color: #666666; font-weight: bold;">\\</span>s*&quot;</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>columns description<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;</pre>
<p>And you can extract more complex data using capture groups:</p>
<pre class="objc"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* source = @<span style="color: #666666;">&quot;&lt;foo no=<span style="color: #666666; font-weight: bold;">\&quot;</span>12<span style="color: #666666; font-weight: bold;">\&quot;</span>&gt;Name&lt;/foo&gt;&quot;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* regex = @<span style="color: #666666;">&quot;&lt;foo no=<span style="color: #666666; font-weight: bold;">\&quot;</span>(.+?)<span style="color: #666666; font-weight: bold;">\&quot;</span>&gt;(.*?)&lt;/foo&gt;&quot;</span>;
<span style="color: #0000ff;">int</span> no = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>source stringByMatching:regex capture:<span style="color: #0000dd;">1</span><span style="color: #002200;">&#93;</span> intValue<span style="color: #002200;">&#93;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* data = <span style="color: #002200;">&#91;</span>source stringByMatching:regex capture:<span style="color: #0000dd;">2</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span>@<span style="color: #666666;">&quot;no: %d data: %@&quot;</span>, no, data<span style="color: #002200;">&#41;</span>;</pre>
<p>This may look like it could be slow to perform matches on the same regular expression twice, but it is not. RegexKitLite is very smart, and will cache your previous matches for very high performance.</p>
<p>RegexKitLite is a very capable, and also much active open source project, with version 3.0 as a release candidate in SVN. Use it, and use it well.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/06/regular-expressions-and-cocoa/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Introduction to  iPhone development</title>
		<link>http://blog.jayway.com/2009/05/01/introduction-to-iphone-development/</link>
		<comments>http://blog.jayway.com/2009/05/01/introduction-to-iphone-development/#comments</comments>
		<pubDate>Fri, 01 May 2009 08:50:37 +0000</pubDate>
		<dc:creator>Christian Hedin</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2920</guid>
		<description><![CDATA[It has been little more than 2 years since the iPhone was first announced and during that time it has managed to make a huge impact on the mobileindustry. 
Introduction
Just recently, iPhone sales figures surpassed all windows mobile phones combined and in several markets the iPhone has been a top selling phone model. Together with [...]]]></description>
			<content:encoded><![CDATA[<p><strong>It has been little more than 2 years since the iPhone was first announced and during that time it has managed to make a huge impact on the mobileindustry. </strong></p>
<h2>Introduction</h2>
<p>Just recently, iPhone sales figures surpassed all windows mobile phones combined and in several markets the iPhone has been a top selling phone model. Together with the launch of App Store, Apple has managed to create a service delivery platform that attracts not only the hardcore users, but also the average Joe. A testament to this is the fact that App Store has had over one billion application downloads with over 50 000 applications available. This large potential customer base, combined with the advantage of having virtually no device fragmentation, makes it quite an attractive platform for mobile application developers. The business model is also lucrative, with Apple offering 70% of revenues from the store to instantly go to the seller of the app without having to pay for distribution or anything else than a one time fee. In this regard, the iPhone has certainly helped Apple put the Objective-C language in the limelight. </p>
<p>For the developer, the transition from higher level languages such as Java may<br />
not be so simple as Objective-C has quite a unique syntax. The goal of this<br />
article is to remedy that by going through the main concepts of Objective-C<br />
from a Java perspective. Hopefully this will help you to get a quicker start in your<br />
iPhone development. You should however be aware that it is equally important<br />
to understand how to use the iPhone’s application frameworks in order to create<br />
applications, this article only scratches the surface of the language you will use. </p>
<h3>Objective-C from a Java perspective </h3>
<p>If you are used to both working in C/C++ and Java you might soon recognize<br />
Objective-C as a middle-ground language, meaning that it provides lower-level<br />
mechanisms than Java while being a more manageable and higher-level language<br />
than C/C++. The language is a strict superset of C, which means it’s possible<br />
to write and compile normal C code using the Objective-C compiler. We also<br />
use pointers (signified in code with an asterisk, *) to objects and not references,<br />
like in Java. For object orientation Objective-C uses a syntax similar to that of<br />
Smalltalk, which might take a little time to get used to if you haven’t seen it<br />
before. Objective-C is a highly dynamic language, much like Ruby and Python,<br />
where it’s possible to change the behavior at runtime. The compiler is quite<br />
forgiving and before getting used to this you will likely discover more problems<br />
during runtime than when using Java. </p>
<p>While some of the features in Objective-C are unique, many of them are<br />
similar to those of Java only named differently. In order to ease the transition,<br />
we will use Java terminology as much as possible and step by step build up a<br />
small example in Objective-C that covers the basic features. In some cases the<br />
examples will keep code from previous examples and in some only the change<br />
will be presented to save space. Regardless, the new code is always in bold font.<br />
Let’s get started. </p>
<h3>Classes </h3>
<p>Unlike Java which uses a single .java file, Objective-C separates class declaration<br />
and definition into two files: .h and .m. The .h file is called the interface, which<br />
shouldn’t be confused with Java interfaces (more on this later). Most importantly,<br />
the interface file lists the methods and member variables that the class contains.<br />
A minimal compilable .h file would look like this: </p>
<pre>@interface MyClass {
}
@end</pre>
<p>This piece of code simply declares an empty interface named MyClass which<br />
you preferably should put in a file named “MyClass.h”. The space between the<br />
“{}” signs is where we will put our member variable declarations and the space<br />
right before the @end tag is where method declarations go. The .m file looks like<br />
this: </p>
<pre>#import ”MyClass.h”
@implementation MyClass
@end</pre>
<p>It’s between the lines starting with @implementation and @end that we will<br />
put our actual method implementations. Notice that there are no “{}” signs<br />
since member variables are declared in the interface file. This minimal example<br />
obviously doesn’t do much but it will compile and it it gives us something to<br />
start with. </p>
<p>Similarly to Java, Objective-C has a superclass that most classes inherit from:<br />
NSObject. But while we in Java are used to an implicit inheritance from this<br />
class, we must here explicitly declare this in our .h files. To inherit a class, we<br />
simply add a colon after the class name in our .h file followed by the name of<br />
the class we wish to inherit:  </p>
<pre>@interface MyClass : NSObject {
} </pre>
<p>Conceptually, NSObject has similarities to java.lang.Object. But it is also more<br />
powerful in the sense that it provides some features that are only possible with the<br />
reflection API in Java. As an example, NSObject allows you to take advantage of the<br />
runtime and determine which methods are implemented. It also contains methods<br />
that are needed for proper memory management such as retain and release which<br />
we will look closer at later on.</p>
<h3>Naming conventions</h3>
<p>Objective-C does not provide any type of namespace functionality like Java does<br />
with packages. Instead, to avoid name clashes, the best way is to use prefixes.<br />
You will see this used heavily throughout the official APIs. NSString (a Foundation<br />
class) and UITextField (of the UIKit framework) are two examples. This makes<br />
it easy to see which classes are written by Apple. We recommend that you use<br />
an abbreviation of your company as two upper case characters and prefix your<br />
classes with that. If your company name is Acme, you could use AC as a prefix. </p>
<p>When programming in Objective-C it is advisable to follow the guidelines from<br />
Apple about naming classes, methods and other building blocks. Typically we<br />
want naming to be very expressive and also highly consistent. This contrasts<br />
Java where, for example, some collection classes use addElement(...) and<br />
sometimes add(...) to add new objects. Consistency makes it a lot easier to<br />
learn the frameworks because they follow the same conventions. We also want<br />
to be expressive and really explain in naming what the class or method does.<br />
Java enforces conventions through JavaBeans standards, but Apple goes far<br />
beyond that. For example, ACPeopleTableViewController would be a suitable<br />
name for a Controller (MVC pattern) class that controls a TableView (standard<br />
component) which contains People. When it comes to methods getters should<br />
not be prefixed by “get” but rather have similar name as the property they are<br />
fetching. If there is a property called defaultColor then the method to get it<br />
is called -(NSColor*)color; not getColor();. There are many other naming<br />
conventions and you’ll rather quickly get used to the standard ones. </p>
<h3>Access Control</h3>
<p>There are three types of access control you can set on your member variables:<br />
private, protected, and public. They have the same effect as in Java. The syntax<br />
for doing this is a bit different tough. Let’s add two member variables to our<br />
header file and make these private: </p>
<pre>@interface MyClass
{
    @private
    int firstNumber, secondNumber;
}
@end </pre>
<p>We simply use the compiler directive “@private” and everything beneath it will<br />
be private until either a “}” or another directive is found. </p>
<p>So how do I make my instance methods private? The answer is that you don’t<br />
have to worry about that, since the language doesn’t formally support changing<br />
the access type on methods. All methods are public!</p>
<h3>Methods</h3>
<p>The equivalent of calling methods in Java is defined as sending messages in<br />
Objective-C. This is one of the big differences between the languages. On the<br />
surface it may appear as we are doing the same thing only with different syntax: </p>
<pre>Java:         myObject.doSomething(myParameter);
Objective-C:  [myObject doSomething:myParameter]; </pre>
<p>But there is in fact a big underlying difference. The doSomething method in<br />
the Java example must exist at compile time or the compilation will fail. The<br />
same does not apply in the Objective-C case. The notion of sending a message<br />
to an object implies that we will send something regardless of whether there is<br />
a receiver or not and how the message together with parameters are handled is<br />
determined at runtime. </p>
<p>Now let’s declare a method in our header file that will add two numbers: </p>
<pre>@interface MyClass {
  @private
  int firstNumber, secondNumber;
}
-(int)add:(int)a to:(int)b; </pre>
<p>The syntax may seem confusing at first but the elegance is displayed once the<br />
method is used to pass a message: </p>
<pre>[myObject add:5 to: 2];</pre>
<p>Notice the readability of that method. Instead of guessing or reading<br />
documentation for method signatures we know right away which parameter<br />
goes where. Now lets add the implementation in the .m file: </p>
<pre>-(int)add:(int)a to:(int)b
{
    return b + a;
} </pre>
<h3>Constructors </h3>
<p>Objective-C doesn’t have the same concept of constructors as Java. Instead,<br />
object creation is divided into two parts: allocation and initialization. There is<br />
no special syntax reserved for object creation (i.e. new in Java). The methods<br />
handling this are regular methods and are named alloc and init respectively. The<br />
two calls are usually nested to allocate and initialize an object on a single line: </p>
<pre>MyClass *myObject = [[MyClass alloc] init];</pre>
<p>Notice the star in front of myObject. This is regular C syntax for declaring<br />
a pointer. Now pointers are usually something that Java people like to avoid<br />
since it can be the source of all kinds of troubles. Fortunately, if you stick to<br />
using Objective-C you almost never have to use the star or any dereference<br />
mechanism when actually using the objects. Just keep in mind that it has to be<br />
there in the declaration. </p>
<p>The alloc method is a static method that resides in NSObject and should never<br />
be overridden. It allocates memory and returns a new instance of the receiving<br />
class. The init method on the other hand is an instance method and should be<br />
overwritten. In fact, the default implementation does nothing but return itself.<br />
The simplest form of init implementation usually looks like this: </p>
<pre>- (id)init
 {
     if ((self = [super init])) {
         /* class-specific initialization goes here */
 }
     return self;
 } </pre>
<p>We always call the parent’s init method and make sure we get something back.<br />
Then we execute our initialize code and return self which is the Objective-C<br />
equivalent of Java’s <em>this</em>.</p>
<p>Just like you often have multiple constructors in Java, you will likely have<br />
more than one initializer in your Objective-C class that takes different types of<br />
arguments. According to convention you should start the name of these methods<br />
with “initWith”. Here’s an initializer that takes two numbers as parameters: </p>
<pre>- (id) initWithNumberA:(int)numberA numberB:(int)numberB
 {
     if ((self = [super init])) {
        firstNumber = numberA;
        secondNumber = numberB;
     }
     return self;
 } </pre>
<p>The convention also says that only one initializer should make the call to super.<br />
It is often convenient to do this in the initializer with the most arguments, and<br />
let the other initializers call that one. Let’s change the first initializer so it looks<br />
like this: </p>
<pre>- (id)init
 {
     return [self initWithNumberA:0 numberB:0];
 } </pre>
<h3>Protocols</h3>
<p>Protocols are essentially the same thing as Java interfaces but with added flexibility.<br />
A class is not always required to implement all methods just to conform to the<br />
protocol, some can be marked as optional. Furthermore, a class can conform to a<br />
protocol by just implementing the required methods, even if it hasn’t explicitly<br />
declared that it is implementing it. Let’s create our own protocol to indicate that<br />
the example class can calculate something, and suitably call it Calculator. We<br />
enter the following in a new .h named CalculatorProtocol.h. </p>
<pre>@protocol Calculator
@required
-(int)calculate;
@end </pre>
<p>The protocol declaration is pretty straight forward. The @required attribute<br />
signifies that the method is mandatory to implement. We could also have written<br />
@optional if we don’t want to force an implementation. It’s also possible to mix<br />
required and optional methods. Now to show that our example class conforms<br />
to this protocol we first change the .h file: </p>
<pre>#import ”CalculatorProtocol.h”
@interface MyClass : NSObject <Calculator>
{ ... </pre>
<p>And then we add the implementation of our getCalculation method in the .m<br />
file:</p>
<pre>-(int)calculate
{
    return [self add:firstNumber to:secondNumber];
} </pre>
<h3>Where’s my garbage collector?</h3>
<p>Unlike Java and desktop Objective-C development there is no garbage collector<br />
available when creating applications for the iPhone. The reason for this is to<br />
allow the best possible performance. This means that you will have to clean up<br />
after yourself manually. Fortunately, the NSObject class contains functionality<br />
to make manual memory management easier. Every object whose class inherits<br />
from NSObject contains a so called retain count which is used to indicate how<br />
many other objects that are using or “owning” it. If you own an object, you are<br />
also responsible for releasing it when you are done, at which point the retain<br />
count willl go down. When the retain count reaches 0 the system will assume it’s<br />
safe to deallocate the memory for your object. So when is the object considered<br />
“used”, i.e. when does the retain count go up? First of all, the retain count will<br />
implicitly increase if you you create the object yourself by using a method name<br />
beginning with “alloc”, “new” or contains “copy”. Secondly, you must explicitly<br />
add one to the retain counter by calling the NSObject method “retain” whenever<br />
you wish to take ownership of an object that you receive by other means, i.e. as<br />
a parameter or from a getter method. </p>
<p>To reduce the retain count, or say that you no longer need the object in question,<br />
you use [myObject autorelease] or [myObject release], where autorelease<br />
signifies that the object should release later. To show how this works we add the<br />
following to our example: </p>
<pre>-(void) setName: (NSString*) newName
{
    [newName retain]; // get ownership, increases retain count for newName
    [name release]; // in case name is already set, we don’t need it anymore
    name = newName; // set name to the new value
} </pre>
<p>We need to retain newName in case we are passing the same object that is<br />
currently assigned to name, or it might be deallocated. When releasing name it’s<br />
possible that it’s not set, but it’s fine to call release on a nil object.</p>
<p>There are situations when you want to autorelease objects. For instance, if you<br />
have a method that returns a NSString that is created inside the method: </p>
<pre>//PROBLEMATIC CODE
-(NSString*)formattedName
{
  NSString *formatted = [[NSString alloc] initWithFormat:@”Name: %@”,name];
  [formatted release];
  return formatted;
} </pre>
<p>If you run this code there’ll be problems. The formatted variable will be released<br />
before it’s returned which means that whoever requested the NSString will get<br />
a pointer to a freed object. The solution is to replace release with autorelease.<br />
Objects that are sent autorelease will be added to an autorelease pool. When<br />
the pool is deallocated release is sent to all objects it contains, including our NSString. The pool is created before events and deallocated when the event has<br />
been handled. That way the formatted variable won’t be deallocated right away. </p>
<pre>-(NSString*)formattedName
{
  NSString *formatted = [[NSString alloc] initWithFormat:@”Name: %@”,name];
  [formatted autorelease];
  return formatted;
}
</pre>
<p>All objects that are not created using alloc, new or copy are automatically added<br />
to the current autorelease pool. So if you don’t want to loose those objects you<br />
need to retain them.</p>
<p>Many objects have convenience methods that return autoreleased objects, so<br />
the easiest solution to our problem would be to avoid the alloc and instead use<br />
a convenience method:</p>
<pre>-(NSString*)formattedName
{
  return [NSString stringWithFormat:@”Name: %@”, name];
} </pre>
<p>Manual memory management is usually one of the tougher parts to get used to<br />
when coming from a “friendlier” language such as Java. It is important however<br />
to get a good understanding in this area as it often can be the source of nasty<br />
bugs. </p>
<h3>Conclusions</h3>
<p>That concludes our example and short introduction to Objective-C, the<br />
language you need to master - or at least learn to use - in order to write great<br />
iPhone applications. The syntax and some concepts differ a bit from Java, but<br />
it’s relatively easy to pick up and get started with. There are many other areas<br />
we haven’t even touched upon, such as the frameworks and tools provided by<br />
Apple. Fortunately there’s a wealth of information available online at the iPhone<br />
Dev Center, where you can read API references, download sample code, watch<br />
tutorial guides and videos as well as discuss with other developers. In order to<br />
develop applications for iPhone you need a Mac computer running Mac OS X<br />
and register as a developer (for free) on Apple’s website. Good luck! </p>
<p><em>Christian Hedin<br />
Stefan Li </em></p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/01/introduction-to-iphone-development/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Adding Sorted Inserts to Cocoa Arrays</title>
		<link>http://blog.jayway.com/2009/03/28/adding-sorted-inserts-to-uimutablearray/</link>
		<comments>http://blog.jayway.com/2009/03/28/adding-sorted-inserts-to-uimutablearray/#comments</comments>
		<pubDate>Sat, 28 Mar 2009 22:39:22 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1441</guid>
		<description><![CDATA[NSArray and NSMutableArray have methods for sorting arrays, NSArray returns new sorted arrays and NSMutableArray can be sorted in place. The sort methods comes in three flavours; using a function, using a selector, or using an array of NSSortDescriptor objects.
NSArray admits to sorts being a slow operation, and adds a method pair for comultive sorts [...]]]></description>
			<content:encoded><![CDATA[<p><code>NSArray</code> and <code>NSMutableArray</code> have methods for sorting arrays, <code>NSArray</code> returns new sorted arrays and <code>NSMutableArray</code> can be sorted in place. The sort methods comes in three flavours; using a function, using a selector, or using an array of <code>NSSortDescriptor</code> objects.</p>
<p><code>NSArray</code> admits to sorts being a slow operation, and adds a method pair for comultive sorts using hints. This way the operation is done in <em>O(P*LOG(P)+N)</em> time, instead of <em>O(N*LOG(N))</em>. Where <em>N</em> is number of elements, and <em>P</em> is number of additions and deletions since the last sort. Unfortunately that do not work on <code>NSMutableArray</code>. So even if memory consumption will not hit the roof, release retain cycles will take it's toll.</p>
<p>So why not add methods to find the insertion points, and insert new objects into already sorted <code>NSArray</code> and <code>NSMutableArray</code> object? Best case for inserting single elements should be <em>O(LOG(N)^2)</em>, so lets hit that target. And on the way there, we will learn how to;
<ul>
<li>Add functionality to standard classes using categories.</li>
<li>Implement high performant Obj-C code for tight loops.</li>
</ul>
<h3>New Categories on <code>NSArray</code> and <code>NSMutableArray</code></h3>
<p>This will become a bit complex on the inside, but the public front should be as simple as this:</p>
<pre class="objc"><span style="color: #339900;">#import &lt;Foundation/Foundation.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingDescriptors:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors;
&nbsp;
<span style="color: #0000ff;">@end</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject sortedUsingSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject sortedUsingDescriptors:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Base Implementation</h3>
<p>We want to follow suit with <code>NSArray</code> and <code>NSMutableArray</code>, so we too shall support inserts based on functions, selectors, and an array of sort descriptors. In practice we only need to implement <code>indexForInsertingObject:sortedUsingfunction:context:</code>, the other methods can use this one, each with a private compare method of their own. So we begin by implementing this method.</p>
<pre class="objc"><span style="color: #339900;">#import &quot;NSArray+CWSortedInsert.h&quot;</span>
<span style="color: #339900;">#import &lt;objc/runtime.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
<span style="color: #002200;">&#123;</span>
  NSUInteger index = <span style="color: #0000dd;">0</span>;
  NSUInteger topIndex = <span style="color: #002200;">&#91;</span>self count<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">IMP</span> objectAtIndexImp = <span style="color: #002200;">&#91;</span>self methodForSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>objectAtIndex:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">while</span> <span style="color: #002200;">&#40;</span>index &lt; topIndex<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    NSUInteger midIndex = <span style="color: #002200;">&#40;</span>index + topIndex<span style="color: #002200;">&#41;</span> / <span style="color: #0000dd;">2</span>;
    <span style="color: #0000ff;">id</span> testObject = objectAtIndexImp<span style="color: #002200;">&#40;</span>self, <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>objectAtIndex:<span style="color: #002200;">&#41;</span>, midIndex<span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>compare<span style="color: #002200;">&#40;</span>anObject, testObject, context<span style="color: #002200;">&#41;</span> &lt; <span style="color: #0000dd;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      index = midIndex + <span style="color: #0000dd;">1</span>;
    <span style="color: #002200;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #002200;">&#123;</span>
      topIndex = midIndex;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> index;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code here...</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>The Objective-C runtime header <code><objc/runtime.h></code> is included so we can go around the usual method dispatch, and instead use the method implementations as function pointers. In most cases this is a neglectable optimization, for this case we will be the bottle neck since we are intended to be the low level API.</p>
<p>The algorithm is a simple binary search, and we have a worst case <em>O(LOG(N)^2)</em> time for index search. Using this for implementing the sibling method in <code>NSMutableArray</code> is as simple as this:</p>
<pre class="objc"><span style="color: #0000ff;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
<span style="color: #002200;">&#123;</span>
  NSUInteger index = <span style="color: #002200;">&#91;</span>self indexForInsertingObject:anObject
      sortedUsingfunction:compare context:context<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self insertObject:anObject atIndex:index<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code here...</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Sort Using Selector</h3>
<p>With functions in place, writing a utility compare function that uses selectors, and can be used with our <code>indexForInsertingObject:sortedUsingfunction:context:</code> method is a breeze.</p>
<pre class="objc"><span style="color: #0000ff;">static</span> NSComparisonResult cw_SelectorCompare<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span> a, <span style="color: #0000ff;">id</span> b, <span style="color: #0000ff;">void</span>* aSelector<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#40;</span>NSComparisonResult<span style="color: #002200;">&#41;</span>objc_msgSend<span style="color: #002200;">&#40;</span>a, <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector, b<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self indexForInsertingObject:anObject
      sortedUsingfunction:&amp;cw_SelectorCompare context:aSelector<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>Notice that <code>objc_msgSend(id, SEL, ...)</code> is used instead of the <code>performSelector:withObject:</code> method. This is a small performance improvement, as what <code>performSelector:withObject:</code> do behind the scene is just a call to <code>objc_msgSend()</code> anyway. We have removed one method invokation per compare.</p>
<h3>Sort Using Sort Descriptors</h3>
<p>Or rather sort with an array or <code>NSSortDescriptor</code> objects. This will be the least performant, but also the most flexible sort. An array of sort descriptors is used because we want to be able to sort using several criteria, one sort descriptor per criteria. For example when sorting on last name, then first name, or even more complex sorts.</p>
<p>A <code>NSSortDescriptor</code> is initialized with a key, sort order (ascending or descending) and optionally a selector to do the comparison with, by default <code>compare:</code>. There are quite a few method invokations involved, and it will be good for performance to avoid as many as we can.</p>
<p>Just as <code>performSelector:withObject:</code> uses <code>objc_msgSend()</code> behind the scene, so do <code>objc_msgSend</code> use a function pointer internally. After doing a hash-table lookup with the selector as key that is. This look-up is cached and very fast, but avoiding it all together is always faster. So let us fetch those when the category is first loaded, and do our calls straight through the functions pointers avoiding at least two or more function calls for each compare operation.</p>
<pre class="objc"><span style="color: #0000ff;">static</span> <span style="color: #0000ff;">IMP</span> cw_compareObjectToObjectImp = <span style="color: #0000ff;">NULL</span>;
<span style="color: #0000ff;">static</span> <span style="color: #0000ff;">IMP</span> cw_ascendingImp = <span style="color: #0000ff;">NULL</span>;
&nbsp;
+<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>initialize;
<span style="color: #002200;">&#123;</span>
  cw_compareObjectToObjectImp = <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSSortDescriptor.html"><span style="color: #0000ff;">NSSortDescriptor</span></a>
      instanceMethodForSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>compareObject:toObject:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
  cw_ascendingImp = <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSSortDescriptor.html"><span style="color: #0000ff;">NSSortDescriptor</span></a>
      instanceMethodForSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>ascending<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>The class method <code>inilialize</code> is kind of magic, it is called once for each class and category, when the class or category is loaded into the run-time. It is the Obj-C equivalent of static initializers.</p>
<p>With the function pointers to the hot-spot method implementations in hand, here is the fast implementation:</p>
<pre class="objc"><span style="color: #0000ff;">static</span> NSComparisonResult cw_DescriptorCompare<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span> a, <span style="color: #0000ff;">id</span> b, <span style="color: #0000ff;">void</span>* descriptors<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
  NSComparisonResult result = NSOrderedSame;
  <span style="color: #0000ff;">for</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSSortDescriptor.html"><span style="color: #0000ff;">NSSortDescriptor</span></a>* sortDescriptor in <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    result = <span style="color: #002200;">&#40;</span>NSComparisonResult<span style="color: #002200;">&#41;</span>cw_compareObjectToObjectImp<span style="color: #002200;">&#40;</span>sortDescriptor,
        <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>compareObject:toObject:<span style="color: #002200;">&#41;</span>, a, b<span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>result != NSOrderedSame<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>!cw_ascendingImp<span style="color: #002200;">&#40;</span>sortDescriptor, <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>ascending<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      	result = <span style="color: #0000dd;">0</span> - result;
      <span style="color: #002200;">&#125;</span>
      <span style="color: #0000ff;">break</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> result;
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingDescriptors:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self indexForInsertingObject:anObject
      sortedUsingfunction:&amp;cw_DescriptorCompare context:descriptors<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<h3>Conclusions</h3>
<p>The fact that Objective-C is a strict superset of C have some good benefits. The obvious one is that your Obj-C code is both source-code and binary compatible with the vast collection of code that has been written in C over the past 30+ years.</p>
<p>The second benefit is that when performance is needed, Obj-C gives us as developers full access to the internals of the dynamic run-time.</p>
<p>But best of all, most developers never need to care. They can, blissfully unaware, reap the benefits of the performance tuning under the hood. Tuning by both Apple and considerate third party library developers willing to go the extra mile (or a few metres at least).</p>
<p>The code is released under BSD license, and works on both Mac OS X and iPhone OS. You can <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/nsarraycwsortedinsert.zip'>download it here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/28/adding-sorted-inserts-to-uimutablearray/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>UIToolbars in iPhone OS 2.x</title>
		<link>http://blog.jayway.com/2009/03/22/uitoolbars-in-iphone-os-2x/</link>
		<comments>http://blog.jayway.com/2009/03/22/uitoolbars-in-iphone-os-2x/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 16:39:42 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1293</guid>
		<description><![CDATA[The new release of iPhone OS 3.0 adds some nice API:s for managing a contextual toolbar. This is well needed as toolbars in the current iteration of iPhone OS is not only poorly documented, it is also quite hard to do right. So I will go over how to do toolbars the right way, for [...]]]></description>
			<content:encoded><![CDATA[<p>The new release of iPhone OS 3.0 adds some nice API:s for managing a contextual toolbar. This is well needed as toolbars in the current iteration of iPhone OS is not only poorly documented, it is also quite hard to do right. So I will go over how to do toolbars the right way, for all who want to implement them the old way before this summer, and for all who think they need to support older versions after then (Read my <a href="http://blog.jayway.com/2009/03/18/iphone-os-and-the-lowest-common-denominator/">previous post</a> on why backward compatibility is not an issue for iPhone OS developers).</p>
<h3>The Problem</h3>
<p>The most intuitive way to create and use a <code>UIToolbar</code> is to add it manually for each of your view controllers. If your application is very simple this could be the right thing to do, but if our application uses a <code>UINavigationController</code> then it is the wrong way to do it.</p>
<p>If you look at the Mail application you will notice how the toolbar stays in place, and the items on the toolbar cross fades when you navigate the application hierarchy. You might also have noticed that the toolbar do not cross fade, but rather is pushed, if you add a toolbar to each of the view trees of your own view controllers. This is because your toolbar is then part of the wrong three hierarchy, as shown in this image.<br />
<div id="attachment_1294" class="wp-caption alignright" style="width: 490px"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/layout_wrong.png" alt="Screen estate as owned by different view controllers." title="layout_wrong" width="320" height="312" class="size-full wp-image-1294" /><p class="wp-caption-text">Screen estate as owned by different view controllers.</p></div></p>
<p>You will find a few solutions if you Goole on the topic, all of them that I have found are dead wrong. They tend to use <code>self.view.superview</code> on the view controller instance to slide the toolbar up one level in the hierarchy. It works, most of the time, but is an ugly hack that is not future proof.</p>
<h3>A Better Solution</h3>
<p>The reason the toolbar is pushed off screen is that the toolbar is owned by the navigation controller,as we saw in the image above, and a navigation controller pushes it's content. The view hierarchy we would like to have is instead something like this.<br />
<div id="attachment_1300" class="wp-caption alignright" style="width: 530px"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/layout_correct.png" alt="Screen estate as owned by different view controllers." title="layout_correct" width="341" height="320" class="size-full wp-image-1300" /><p class="wp-caption-text">Screen estate as owned by different view controllers.</p></div></p>
<p>In this setup the navigation controller can push the content, as it is intended to do, and the custom toolbar controller can manage a static <code>UIToolbar</code> with cross fades. Only problem is; this custom toolbar controller do not exist, and we must implement it on our own. Luckily not many lines of code is needed.</p>
<h3>Custom Toolbar Conroller Requirement</h3>
<p>The custom toolbar controller should be a subclass of <code>UIViewController</code>, that way it's fits nicely into the Cocoa Touch framework, and can nicely be fitted into any well written application.</p>
<p>The custom toolbar controller should manage a view consisting of a <code>UIToolbar</code> instance, and a view that is fetched from another view controller. This is modelled after how a <code>UINavigationController</code> manages a view that consists of a <code>UINavigationBar</code> and the view fetched from other view controllers. This way any well written view controller can be used with our custom toolbar controller.</p>
<p>Lastly our custom toolbar controller should implement the <code>UINavigationControllerDelegate</code> protocol, so that we can listen to events as view controllers are pushed and poped from the navigation stack, and update the toolbar with contextual toolbar items. Just as the navigation controller updates it's title by fetching the title property of the managed view controllers, so will our custom toolbar controller update the toolbar items by fetching the toolbarItems property if available.</p>
<h3>Toolbar Controller Interface</h3>
<p>The interface will be sparse, all we need is an initializer for creating a toolbar controller with another view controller providing the main content, and for sports two properties to access the content view controller, and the toolbar itself.</p>
<pre class="objc"><span style="color: #339900;">#import &lt;UIKit/UIKit.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> CWToolbarController : UIViewController &lt;UINavigationControllerDelegate&gt; <span style="color: #002200;">&#123;</span>
<span style="color: #0000ff;">@private</span>
    UIViewController* _contentViewController;
    UIToolbar* _toolbar;
<span style="color: #002200;">&#125;</span>
&nbsp;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> UIViewController* contentViewController;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> UIToolbar* toolbar;
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithContentViewController:<span style="color: #002200;">&#40;</span>UIViewController*<span style="color: #002200;">&#41;</span>contentViewController;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Toolbar Controller Implementation</h3>
<p>The grunt work for implementing the toolbar controller do not need any further explanation.</p>
<pre class="objc"><span style="color: #339900;">#import &quot;CWToolbarController.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> CWToolbarController
&nbsp;
@synthesize contentViewController = _contentViewController;
@synthesize toolbar = _toolbar;
&nbsp;
- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithContentViewController:<span style="color: #002200;">&#40;</span>UIViewController*<span style="color: #002200;">&#41;</span>contentViewController;
<span style="color: #002200;">&#123;</span>
    self = <span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>self<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        _contentViewController = <span style="color: #002200;">&#91;</span>contentViewController retain<span style="color: #002200;">&#93;</span>;
        <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>_contentViewController isKindOfClass:<span style="color: #002200;">&#91;</span>UINavigationController <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>UINavigationController*<span style="color: #002200;">&#41;</span>_contentViewController<span style="color: #002200;">&#41;</span>.delegate = self;
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span>
	<span style="color: #0000ff;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code here...</span>
&nbsp;
- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>dealloc;
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>_contentViewController release<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>The first interesting code is to setup the view that is managed by our toolbar controller. This view have two subviews, a <code>UIToolbar</code>, and a view that we fetch from the content view controller we where given. We do this setup in the <code>loadView</code> method.</p>
<pre class="objc">- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>loadView;
<span style="color: #002200;">&#123;</span>
    UIView* contentView = _contentViewController.view;
    CGRect frame = contentView.frame;
    UIView* view = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIView alloc<span style="color: #002200;">&#93;</span> initWithFrame:frame<span style="color: #002200;">&#93;</span>;
&nbsp;
    frame = CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">0</span>, frame.size.width, frame.size.height - <span style="color: #0000dd;">44</span>.0f<span style="color: #002200;">&#41;</span>;
    contentView.frame = frame;
    <span style="color: #002200;">&#91;</span>view addSubview:contentView<span style="color: #002200;">&#93;</span>;
&nbsp;
    frame = CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #0000dd;">0</span>.0f, frame.size.height, frame.size.width, <span style="color: #0000dd;">44</span>.0f<span style="color: #002200;">&#41;</span>;
    _toolbar = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIToolbar alloc<span style="color: #002200;">&#93;</span> initWithFrame:frame<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>view addSubview:_toolbar<span style="color: #002200;">&#93;</span>;
&nbsp;
    self.view = view;
    <span style="color: #002200;">&#91;</span>view release<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>_toolbar release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>This code reuses the screen setup already done by the content view controller, and re-layouts our subviews. It is a simple solution, and you will need a custom class for the root view with an overloaded <code>layoutSubviews</code> if you want to properly handle orientation changes. But I have left this out, as it is not within the scope of this post.</p>
<p>Next up we need to update the toolbar with contextual toolbar items, when our content changes. This is only supported if the content view controller is a <code>UINavigationController</code>, as can be seen in the initializer above. This could be made more flexible, but is also outside the scope of this post. We have set our toolbar controller to be the delegate for the content navigation view controller, so all we need to do is to respond to navigation events as they occur. </p>
<pre class="objc">- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>navigationController:<span style="color: #002200;">&#40;</span>UINavigationController *<span style="color: #002200;">&#41;</span>navigationController
        willShowViewController:<span style="color: #002200;">&#40;</span>UIViewController *<span style="color: #002200;">&#41;</span>viewController
        animated:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>animated;
<span style="color: #002200;">&#123;</span>
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>* items = <span style="color: #0000ff;">nil</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>viewController respondsToSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>toolbarItems<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        items = <span style="color: #002200;">&#91;</span>viewController performSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>toolbarItems<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#91;</span>_toolbar setItems:items animated:animated<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<h3>Conclusion</h3>
<p>As shown with this code, doing the correct way with Cocoa Touch almost always means doing it in the easiest way as well. The hard part is knowing what the correct way is. My hope is that this post can guide you in the right direction. Rule of thumb is to always try to follow the same pattern as similiar things in Cocoa, it might feel like it is harder to do, but at the end of the day you will end up with less code, with more features.</p>
<p>The code above for implementing the custom toolbar controller, is much less code than what is needed to write a small application to demonstrate it being used. I have therefor made a small demonstration application with this complete code. It is a tree of table views, where each item opens up a new table view tree with one less toolbar item. </p>
<p>The source code is released under BSD license, and you can <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/toolbarapp.zip">download it here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/22/uitoolbars-in-iphone-os-2x/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
	</channel>
</rss>
