Thursday, May 30, 2013

To Xib or Not to Xib?

Being new to iOS environment, I watched different tutorials: the latest Stanford iOS classes uses storyboard for almost all demos, reading big nerd ranch iOS programming book, Interface Builder (xib files or in their binary form nib file) are much prefer over storyboard, looking at source code in TODO sample none of those methods are used. Everything is crafted by hand, which I will call in the rest of the blog the hand-crafted approach. Which one to choose?

First of all, all of them work, it's just a matter of finding which one works best for you. Which can you app are you making? Are you working alone? Are you an addicted to IDE or you'd rather use plain old text editor? Are you more a mouse person or a a do-it-all-with-the-keyboard guy?

I try the different ways with one simple example: I want to build an App that displays a list of item. We want to create a ViewController named MyViewController which inherits from UITableViewController. All source code could be found here.


Step1: Create Xcode project with empty template

Open Xcode and go to File -> New Project, select the  Empty Application template

Step2: Add new file MyViewController

and make it extends UITableViewController

Step2: Link MyViewController to AppDelegate 

By adding property at line 4:
@interface MyAppDelegate : UIResponder 

@property (strong, nonatomic) UIWindow *window;
@property(strong, nonatomic) MyViewController *viewController;


Step3: Take care of initialisation of AppDelegate

Once the application is loaded, it's the developer's duty to instantiate MyViewController. As per commonly used Delegate pattern, once app is loaded the delegate method application:didFinishLaunchingWithOptions: is called. Within this method, you should add line 6-7
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customisation after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    self.viewController = [[MyViewController alloc] initWithStyle:UITableViewStylePlain];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;

Step4: Implement your model in MyViewController

For the example we feed an array of fake data in it setter method.
@implementation MyViewController
NSArray *_items;

- (NSArray *)items{
    _items = [[NSArray alloc] initWithObjects:@"Item No. 1", @"Item No. 2", @"Item No. 3", @"Item No. 4", @"Item No. 5", @"Item No. 6", nil];
    return _items;

Step5: Display your model in MyViewController

To display the content od a cell you need to conform to protocol UITableViewDataSource, tableView:numberOfRowsInSection:  and tableView:cellForRowAtIndexPath: are the two methods responsible for the display of a cell.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.items count];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell;
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    // Configure the cell... setting the text of our cell's label
    cell.textLabel.text = [self.items objectAtIndex:indexPath.row];
    return cell;
That's it you're all done, run the app!

Interface Builder

Xib, nib depending if it's the next generation or not. Actually xib file is the xml source file which describes your view. Nib being the compiled version.

Step1: Create Xcode project with Single App template

Open Xcode and go to File -> New Project, select the Single View Application template

In the next step make sure you have the option Use Storyboard unchecked.

No need to add code in AppDelegate's application:didFinishLaunchingWithOptions:, the code has been added for you. See line 5-6.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[AGViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;

Step2: Implement your view with xib view

1. drag and drop Table view from object library in utilities bar.

2. create an outlet, drag and drop (with control key down) up to MyViewController interface.

3. link data source to file owner: right click on TableView all the way to file's owner in document view.

Step3: Implement your model in MyViewController

Same code than Hand-crafted approach step4.

Step4: Display your model in MyViewController

Same code than Hand-crafted approach step5.

Run the app an you will have the same result. As you can see there is less code to write, but the approach involved more mouse actions. One piece of code that was generated for you but which is important to understand is in step1, the call to initWithNibName:bundle:; One interesting stuff with Interface Builder is that you can mix handcrafted and interface builder. The strength of a WYSIWIG widget based tool like Interface Builder is to build complex customized view. If you have to build a Custom Cell for you TableView, you could use Interface Builder and then load the archive and associate it with the relevant object.


Introduced in iOS5, Storyboard carries on the WYSIWYG approach launched by Xib. Sometime seeing as a replacement of nib, it brings UI definition in one simple file rather than several xib files, also deal with transition between screen.

Step1: Create Xcode project with Single App template

Same as for Interface builder, but this time make sure Use Story board option is checked.

Step2: Make connection from storyboard to your code

1. Go to .storyboard file, select the UIViewController graphic
2. On the utilities tab, in the identity inspector, change the class field to match MyViewController
3. create an outlet: holding the ctrl key with a drag from your view in storyboard to MyViewController.h file. Once you drop you will be prompted to enter a name, and click connect. this is the magic part of Apple WYSIWYG editor and how the link to source code. All newbies get surprised here.

Step3: Connect the datasource with outlet

Remember for hand-crafted we had to implement 2 protocols data source and delegate one. Same thin here, right click on TableViewController in the storyboard. From the outlet section, drag and drop to My Table view controller. Do it for data source and delegate.

Step4: Implement your model in MyViewController

Same code than Hand-crafted approach step4.

Step5: Display your model in MyViewController

Same code than Hand-crafted approach step5.

Run the app an you will have the same result. Here again, there is less code to write, but the approach involved more mouse actions. Besides, I thing the strength of storyboard comes when you have an application with several views and transitions using segues.

As a conclusion, we've seen the different approaches, I think to start with it's easier with the hand-crafted approach as you get to understand frequently used patterns in iOS like the Delegate pattern. But then I might be biased as I have a developer background. I like the idea Xcode storyboard/xib approach , I think it's nice to prototype or to experiment (like a preview you see it right away) but at the end of the day I find source code easier to maintain. It's all written in plain code. But you know what, storyboard/xib file are be all written in plain XML too ;) Right click and open then as source code.

Do you prefer to write XML or Objective-C?

Thursday, May 23, 2013

Delving into iOS for a week

I've been curious about writing native mobile apps for a while. 

In term of programming background, I've travelled from C++, to Java, naturally made my way to Groovy - experimenting other JVM based language is fun- and lately, I have been more involved in JavaScript. With web development  experience, writing HTML5 web mobile app is so much fun: playing around with jQuery mobile, cool HTML5 capabilities, JS framework variety... And if you really want it on web store, use Cordova for packaging it into hybrid app.

But still, it is not the same 'look and feel' and user experience. So, I'd like to know what it takes to write native apps. Apart from Cordova, I have no real experience with native apps...  And I've got this brand new iPad mini from my birthday.

Let's take a deep breath and make the plunge. Delving into iOS for a week. No fear. What can I learn in a week?

Googling around, looking for books to read, I eventually bought ePub version of Programming in Objective-C. I started reading it from start (you've got to do things right, you're learning a new language, take it seriously) and then... I just jumped to random sections. I was too eager to investigate "new" stuff like protocols, dynamic typing and blocks.

Objective-C sounds familiar. Indeed, Objective-C is a superset of C; My first surprise comes on how you call a method on an instance. You actually don't call a method, you send a message. I found this interesting blog discussing it: it's not just syntax hype! Digging around, I learn Objective-C derives its object syntax from Smalltalk. The difference between calling a method in C and sending a message in Objective-C is in how the code referenced by the method or message name is executed. In C/C++ language, methods are (in most cases) bound at compile-time whether in Objective-C, the target of a message is resolved at run-time which brings me to dynamic typing! Man I love that. Just like in Groovy (did I already mention I'm Groovy addicted? Co-founder of RivieraGUG :-) ?) you've got the type id, same as def (I don't really like the name here. Id makes you thing of unique identifier) which means a pointer to unknown object (see the difference from void *). Dynamic typing offers a wide flexibility in a way you can design you program. Another very close concept Obejctive-C/Groovy is categories: even the syntax is close!

Second surprise (I'm less enthusiastic about it, yo be honest) comes with property vs instance variable. It's obviously nice not to have to write your getter/setter methods yourself although with lazy instantiation pattern you often do write them and then you end up needed to use synthesize keyword which I find a bit verbose. Not to say all the keywords you have to precise around your property. I definitively think there is room for improvement here. Properties bring me to memory management, another topic is  worth digging, but I work with iOS6 and I use ARC (autmatic reference counting) so I can delay that for next week . Enough theory.

Launching Xcode to build command line application is ok for the first day. But I soon get frustrated, the fun of mobile app is mostly in graphical app. Games.

I remembered a recommendation from a friend of mine to follow the Stanford iOS classes. Those classes are available on iTunes. You can download them for free. And guess what? From the first lecture you start building a matching card game: Matchismo. That is what I want! Stanford classes are 19 sessions of 1h-1h30 each. During the lecture, you go through Objective-C concepts, Foundation libs, and Cococa Touch libs at the same time. Live demos are really good - my preferred part - I don't have time for the assignments but I like live coding at the same time than Paul Hegarty (Fortunate I have the pause option). With the video comes the very detailed slides with annotated screen shots (amazing learning support) and assignments. You can read this blog great post on 2011 classes if you want further feedback.

The good part of video classes is that it's easier to learn a tool like Xcode. In a book, you're flooded with screenshots when it comes to explain Xcode. I'd rather watch a video than going through pages of text and photos. I didn't have time to watch them all - went through half of them - but I will carry on for sure.

Starting a new project in Xcode, using storyboard and you get a feeling of language workbench. You're so well assisted by the IDE that you're not just writing code, you're drawing code: you're holding ctr key + drag and drop to generate action and outlet, Xcode interacting with you which name you want to give etc...  You're manipulate the abstract representation of a program with the tools provided by the editor. You code feels like natural language. You can pick very descriptive variables name, you're so well assisted by Xcode auto-completion that you can think in higher abstraction level.

Eventually, what did I manage to do?
After a week I manage to write my first game: Visualize (really inspired by classes). I even get through apple certificate hell to get my app running on my device. Horray! I didn't have time to publish it though(not enough polished to be published to App Store).

If you starting on iOS, with some OO programming background, I would definitively advise you to:
- watch  iOS Stanford classes,
- get your hands into code from day one.
- and have fun!

Tuesday, May 7, 2013

Reading about AngularJS - part 1

AngularJS, Google last breed MV* framework, is getting a really good momentum. Proof is this spring,  several books are coming out.

And, this is great news!

I remembered getting my hands on AngularJS for the first time, a couple of months ago. I started with the online documentation and with the mailing list. I also went a few time on IRC chanel, which is fun and the ultimate interactive approach :) One thing I particularly like is the usage of jsFiddle and  plunker for describing an issue in the mailing list or giving examples in the online documentation. What's better than thousand words? Code of course ;-)

Even though mailing list  and getting your hands into code is a great way to learn, I like getting my tablet in the evening and reading about the subjet. It gives a general understanding of the philosophy behing a framework, it also opens your mind by teasing you with paths to explore, different ways of doing stuff.... My blog post is actually not about AngularJS but more about AngularJS' books!

Available books

More recently, googling "angularjs books", to my pleasure gives me choices; at the time of writing this article:

- AngularJS - O'Reilly - Brad Green and Shyam Seshadri, completed book.
- Recipes with Angular.js - LeanPub - Frederik Dietz, RAW mode.
- Instant AngularJS Starter - Packt Publishing - Dan Menard, completed book.
- AngularJS Web Application Development - Packt Publishing - Pawel Kozlowski and Peter Bacon Darwin, RAW mode.
- AngularJS in Action - Manning - Brian Ford and Lukas Ruebbelke - to be available in Fall 2013,.

So I picked a couple of them, here is the ones I've read or I'm still reading for RAW mode ones:

AngularJS by Brad Green and Shyam Seshadri

One of the first book to be available on its completed form, written by 2 engineers from Googles Inc., I like the book, specially if you're completely new to AngularJS.

It's an 200 pages book with a nice step by steps approach. You should read it from start to end. With an amazing fast first chapter, giving you all the vocabulary to work with Angular, from templating, to data binding to dependency injection....

Chapter 2 get deeper and introduce AngularJS life cycle and how two-ways binding is achieved. In this chapter you've got AngularJS in a nutshell. I like the offline talk about unobtrusive JavaScript because that was exactly one of the point that bothers me when starting with the framework, I'm best practices addicted:)

Chapter 3 talks about the tooling which could have been interesting but to me it's the part of the book I like the least because it's going fast on Batarang, Yeoman, IDE and it's developing "Integrating AngularJS with RequireJS" which, to me, is not so much required.

Chapter 4, we're building GutHub application, all source code being in GitHub. Nope guys I didn't misspell, it's GutHub we're buiding  :)
Great intro to promises implementation in AngularJS with chapter 5 and directives look so simple to implement in chapter 6. Chapters 7 gives miscellious tips. Chapter 8 gives different sample apps, to be honest, I've skipped that one. 

Recipes with Angular.js by Frederik Dietz

As the title says it all: it's a recipe book, man. And indeed, if you look for a AngularJS concept you'll find a couple of examples about it. Source code is available in github which is great. Being published online, I wish we could have HTML links for code snippets, but fine enough once you've got github link all examples are ordered by recipe number. I like also clear proble/solution/discussion pattern. I wish it was a bit more verbose from time to time.

This book is not intended at giving an introduction on the framework. It's more a book you use by index.

At the time of writing the book is still on RAW mode with 100 pages. I expect more recipes to come. It's the diversity and broad coverage of recipes that makes the book rich and useful. Keep up with the good work Frederik.

AngularJS Web Application Development by Pawel Kozlowski and Peter Bacon Darwin

So far I've read only half of it. The book being still in RAW format, I've read chapter 8 before chapter 5. But I found the book quite promising. Once I've got the final version, I'll go over it again but in the right order, just for the pleasure :)

Chapter 1 is brillant, it gives you the philosophy behind the framework: declarative template view vs imperative controller logic paragraph is really worth reading. Crash course talking about 2-ways data binding, hierarchy of scopes: great! The discussing on Dependency Injection which gives a list of the different ways of achieving it with AngularJs is already advanced.

Chapter 2 is really about best practices in web application development and how they apply to AngularJS. Best part, being about Karma (still named Testacular in the book), this book just not speaks about test driven development,  it applies it! All book samples start showing the expected behaviour and then the code sample. To my surprise, the book sample angular-app is not following directory structure generated by Yeoman, with a bit of research I find the explanation in this thread on "by features" layout.

Chapter 3 is a bit off topic with CORS topic although nice to read but when it comes to promises, it is a real pleasure, it really goes deep in the explanation. Chapter goes on about $http and $resource services.

Chapter 5 makes routes and views clear to me which was one of the subject I was looking after. Delving into history API and HTML5 push state, you can understand how views can be routed using $routeProvider object so that you can achieve deep-link (navigable URLs) either using hashbang or HTML5 mode. To bing us to Angular routing service, the authors take a experimental approach coding a hand-crafted navigation bar using $location and ngInclude directive, and then later switch to $routeProvider and ngView. So you can truly understand the benefits of it. Paragraph on limitations of routes services is worth reading. It gives the starting point for the new AngularUI project ui-routes.

Chapter 8 on forms is full of details recipes directly available online. With this chapter you delve into details (such as validation) which gives the feeling to the reader: the book can also be used as “reference”. I like the details code snippets: you learn small tips and tricks. Very geek.

I'm still reading Chapter 9 and 10 about directives. This is the part where you teach your browser tricks. It's Angular way of taking the web from a different angle. Approach those chapters with a "read, play with it and read again" pattern.

As core comitters to AngularUI, I wish Pawel and Peter had written a full chapter on it. But maybe it's for a future project: write another book on AngularUI :-)

On conclusion, if you you want a book to have a general overview go for AngularJS from Brad Green and Shyam Seshadri. Interesting in "how to" style, google and use jsfiddle examples or go for Frederik Dietz's Recipes book. For a more deeper delve into AngularJS I would definitively go for AngularJS Web Application Development's book from Pawel Kozlowski and Peter Bacon Darwin. But...

For fall 2013, we'll have AngularJS in Action. I am looking forward to reading this one. this is the reason why I put in my article title: part 1. Stay tune for a "Reading about AngularJS - part 2" blog post!