Understanding M-VC in iOS

Posted: January 28th, 2012 | Author: | Filed under: iOS | 2 Comments »
This entry is part 4 of 4 in the series iOS Beginner blog series

MVC in web programming
I also assume that you know enough about MVC, or atleast understand separation of concerns in code structure. For Rails or CakePHP developers, this concept is already at the back of your mind.

So here’s my own simplified definitions of MVC:
Model : Data object classes, entities in your system/app, containing attributes. Eg: BlogPost class
Controller : The ‘director’ of Models, tell them how to move around and interact with others. Eg: A class that updates a BlogPost
View : The result of the interactions. What you see. Doesn’t really matter if you can’t see. The interaction happened anyway. Eg: A class that displays updated message.

M-VC in iOS apps
In iOS app development, Models are still Models, they are still data objects on their own. What’s different is that View and Controller are usually together, in a single class. The reason is that most of the time, the interaction that modifies your data object (by controller) usually followed by a change in UI *immediately*. An even simpler way to put it is that a single function call has to delete a BlogPost object and remove the table row at the same time.

The difference became much more apparent to me after months of learning how to craft great user experience, especially in the case of handling asynchronous remote data. These are the very essential steps of handling remote network connection:

  • Start a network connection
  • Update UI to show ‘waiting’ state
  • … nothing happens, wait
  • Connection finishes, parse and store data
  • Update UI with data

Besides, you also need to consider what to do when connection fails:

  • Why it failed? Should retry or abort?
  • Should update UI to show retrying state or show an error message
  • Can the user re-initiate the connect on UI

There are a lot of steps, the ones in italic are the responsible of a View, while others are handled by Controller.

In web development, you make a request, the Controller decides what to do with Models, then passes result to the View to display the state or changes. It’s not the same in iOS app. The changes to a View happens immediately when properties of Models changed. That is why in iOS app, the ViewController exists. In a broad sense, the lines of codes that should belong to View and the lines of codes that should belong to Controller are intertwine and inseparable.

To put the concept in real life. An application that fetches a number of blog posts from server and display them in a table would likely to have following 4 files


So this post introduced the ViewController way of thinking in iOS app. Take your time to apply the concept, look at some of the examples and try to guess which lines do the job of a View, which lines do the work of a Controller. It will serve as a solid foundation for organising your code.

While this is a good concept to understand. I remember that I did not really bother about it, instead, I wonder why the heck there is (UI)View when there is (UI)ViewController. And then there are stuff created inside a .xib with Interface Builder. As a beginner in a difficult programming language, I’m sure you are more drawn to use IB to create your controls. But then you are left with questions like:
– How to not use .xib?
– How to link a class with .xib you created after, what’s the real connection between them?
– Why some developers are against it, why some use it all the time?

In the next post, I will attempt to introduce the fundamental differences between UIView, UIViewController and how they are related to .xib files, Why Interface Build is good in some case, why it is not in some other.

Thanks for reading. You can now subscribe to my blog via email using the form on the right hand side.

End of 2011, the Lunar New Year version

Posted: January 23rd, 2012 | Author: | Filed under: Personal | 2 Comments »

It’s the new year of 2012, lunar calendar that is. In case you are not aware, in my culture, Lunar New Year celebration is a huge thing, as many as 3 days off before and 7 days off after, like in China. So while having a few days off, I thought I should write something about the 2011 and prepare my todo list for 2012.

My 2011 started with a fantastic closing off of super happening 2010: Laying down IT foundation for TGM VN, producing the best Final Year Project of the year with my brother, while finishing off my degree at NUS.

I wasn’t sure what I did was entirely what I wanted. I felt that I needed to take a break from all that and more importantly embark on a self-exploring journey for myself. That’s when I took the opportunity to work at Anideo, a private startup funded by Eduardo Saverin. It’s almost a year now.

To summary it all, there weren’t many significant events that I could recall over the year but I’ve learnt a lot of extremely valuable lessons both in the profession that I’m in and personally.

Learning iOS development probably is the best thing

I’ve shifted my interests from web development to mobile app development. If you have not read my previous post about how I started this, you should now. It is so much more challenging both technically and economically. And ofcourse, the more challenging, the more rewarding it is at the end. I’ve produced, in my opinion, a few amazing apps in the process.

Not only I’m getting more confident in my technical skills, iOS development taught me so much more about UX design, UI design, delivery process, handling users’ feedback and complaints.

Stay hungry, stay foolish

Well, I know this quote is boring as it has been quoted and requoted so many times since Steve’s speech in 2005. However, ask yourself this question: do you really live it?

A few weeks ago, I caught up with a friend. During our conversation, he told me that one of the projects that I’ve put together in 2010 is still in use today and still no one could really out-do it after more than a year. The next moment after hearing this, my mind shifted into excited gear and the very next thought that came into my mind was: “I want to rebuild it, better”. It never occur to me that I need to stop and receive the credit I’ve earned. I have always wanted to do the next ridiculous thing just because people think it’s not possible. Once I finished something, the following few days are always depressing because I have nothing to do.

It’s one of the greatest phrases that describes very accurately how I work. I’m always hungry for more and I always do the things that people considered impossible. So 2011 taught me that as long I am still walking, I could never stop, and somehow I can always pull off the stunts.

Working in startup is damn f**king hard

Every user’s complaint makes you feel so damn bad about yourself. Everyday, receiving bad daily stats is depressing. Every missed deadline makes you think there’s no tomorrow. Sometimes you do a lot yet it doesn’t feel even close to enough. Sometimes you want stop to think but it makes you feel so bad because you just want to do something.

You hear stories about how people can wear anything to work, coming to work late, and work wherever they want. It’s true but it’s just the surface, there are more than that. The responsibility is so much more than an office job. You can’t just stop working when your idea is half-finished.

You also hear so many success stories every single day and keep wondering when is your turn. The reality is that those are only less than 1% of many companies out there. The other 99% *will* fail.

In short, you’ll get so many more downs than ups, and it never ends.

Stop giving excuses and just do it

It constantly amazed me every single time I put my thoughts into this. Over the last 2 years, I’ve learnt to stop giving excuses for my mistakes, I’ve learnt to stop making complaints about things people do. I just shut up and find another way around doing things. That alone gave me so much more energy and getting so much more things done.

Look around you, look at people who you think are somewhat achievers, how many times do you hear they complain about their daily life? Once you realized this, the pattern is pretty interesting. Yet people just don’t get it.

My moto has always been: don’t ask, don’t complain, just f**king do it already. As simply as that.

… and that concludes my 2011. My 2012 is going to be explosive!

PHP/Rails to iOS, what are .h and .m files?

Posted: January 21st, 2012 | Author: | Filed under: iOS | 9 Comments »
This entry is part 3 of 4 in the series iOS Beginner blog series

Since I began my iOS beginner blog series, I have been receiving tremendous feedback and appreciation from readers all over the world and lots of encouragement for me to continue with the series.

I started realizing that there are so many more developers out there who are struggling with iOS than I originally thought. So allow me to make my point very clear that this blog series is meant for beginners, sometimes certain statements might not be technically correct, but I intentionally wrote them in a certain way so as to simplify the thought process for new readers. Those ‘mistakes’ will not do any harm, as long as you keep progressing, the more advanced concepts will help you redefine those yourselves. In this post, I will make some of those in the process of explaining the concepts. This post is a highly simplified and short explanation for absolute begineer who have not touched any compiled language before iOS development.

The big question, unanswered

Just like you, I stumbled right at the first step of understanding iOS source code. With no background in compiled languages, I can’t really tell what are the purposes of different files. Java programmer would have no problem understanding all the declarations like @interface, @protocol, @implementation. (Don’t worry, my next post will talk about these in more details). PHP programmers, well, everything ends with .php

Unfortunately, the question “What are .h and .m files?” that I seeked is too fundamental that seasoned developers don’t really bother answering. I found some really short answers for this question here and here but they didn’t really help me much.

There are many many more questions like this along my journey of learning iOS. Until now I’m still puzzled why there aren’t many people that could help guiding beginners in the transition from web languages to compiled Objective-C language like this. StackOverflow is an excellent repository of even weirdest questions, but there ain’t many basic concepts explained well. Having to gone through the pain, now I am hoping to demystify some of these concepts for the absolute noobs like I was.

So what are .h and .m files?

.h file is header file, .m file contains the implementation

Each class in Objective C, usually made up by one .h file and one .m file.

The .h files are header files. It is called header file because it only contains the ‘head’ or a class, in other words, all the properties and functions that any other outside class should know about, the ‘public face’ of a class. It does not contain implementation logics at all.

On the other hand, .m file contains all the implementation details of all the functions declared in .h and more. It also contains declaration and implementation of private functions that outside classes cannot use, or should not care about.

How to ‘use’ these files, a simplified perspective

You got yourself a pair of .h and .m files, downloaded from Internet or someone send it to you and tell you to figure it out by yourself, either way you only have the files and no documentation. So you wonder where to start to get a big picture of what it does. This happens more often than you think. As a more seasoned developer now, I still find myself downloading open source projects and look at how some of the classes are implemented all the time, mostly from cocoacontrols.

First, you need to tell the names and parameters of functions. This is where my previous post came in very handy.
Secondly, you should start to *only* look at the .h file. Because this file contains the public interfaces of a class that the writer wants others to know. There are a lot of things inside a .h file but most important are the functions. They look like these:

// Convenience constructor
+ (id)requestWithURL:(NSURL *)newURL;
+ (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache;
+ (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache andCachePolicy:(ASICachePolicy)policy;
// Run a request synchronously, and return control when the request completes or fails
- (void)startSynchronous;
// Run request in the background
- (void)startAsynchronous;
// Clears all delegates and blocks, then cancels the request
- (void)clearDelegatesAndCancel;

This is taken direct from ASIHTTPRequest network library that I used for my latest projects.
And as you can probably tell, the snippet describes how to create a connect, start it and then stop it. It is pretty much all the basics that you need to make use of the class. Luckily a lot of library developers out there do include one-line comments like this in their public interface, they are really useful.

You only need to look at .m files if you want to understand or copy the implementation of the classes.

The import statements

At the beginning of all the files, you will need to import the .h files that you are working with. This is because Object-C is a compiled language, you need to tell the compiler what are the objects that you will be working with, more importantly the compiler need to know the exact interfaces available in those files in order to compile them in your current class. If you manage to compile successfully code that contains a call to a mis-spelt function name, your app will crash! (There are ways to do this).

At this point, you only need to know that whenever you need to call external classes, you need to import their .h files.

So now you can walk to your nearest iOS noob friend and pretend that you know everything about the class that he is working on just by looking at the .h file and quoting some function names. What’s cooler is that you can even ask why not declare them slightly different… that is before he shoots you down with questions you don’t even understand.

You can now subscribe to my blog using the form on the right column. Thanks for reading, do share it with your fellow iOS coder too.

PHP to Objective C, where the f**k are parameters?

Posted: January 16th, 2012 | Author: | Filed under: iOS | 22 Comments »
This entry is part 2 of 4 in the series iOS Beginner blog series

Javascript, PHP, Ruby functions

I assume you are very familiar with declaring functions in any of the languages above, if not, you should not be reading this. Let’s begin with a simple function to send email in these languages:

// PHP or Javascript
do_send_email (recipient, cc, subject, body);
// Ruby
do_send_email (recipient, cc, subject, body)

So it’s clear by looking at the function’s signature that it takes 4 parameters and they could be optional, depends on your implementation. Even if you missed one parameter, in most cases it is fine, no complain, no fatal error.

First encounter with Objective-C

Below is one example of Objective-C function calls

[[UILabel alloc] initWithFrame:CGRectMake(0,0,120,35)];

This is the kind of code I see the most when I first opening up a source file and try to read Objective-C syntax. And I’m sure this is the case for many of you right now.
Now, the biggest problem is that you cannot even tell what it is, left alone guessing what it does. Obviously, I couldn’t tell and that was why I had to ask myself “where the f**k are parameters?”. Because then I can somewhat guess what function it calls.

Unfortunately for me, no one told me that I’m way ahead of myself. So I’m tell you now: Stop guessing! Go back to the basics before continue reading this.

As mentioned in the beginning of the series, I’m not writing a tutorial series, I’m writing about the WHYs of the language, in a way more fundamental than even knowing the syntax itself.

The function’s full name

This is where it gets interesting. For an email sending function call similar to that of PHP:

[emailSender doSendEmailToRecipient:(NSString*)email cc:(NSString*)cced_email subject:(NSString*)subject_to_send body:(NSString*)body_to_send];

The function’s entire name is doSendEmailToRecipient:cc:subject:body: and *not* just doSendEmailToRecipient

Strict and brilliant by design

The Objective-C function’s name is designed to include the parameters’ names. This is not the case with most web programming languages.
Why does it have to be this way? The obvious reason is Objective-C is a compiled language, once you get it wrong, it cannot even be compiled.

However, the more important reason, the motivation of this post, and one of my most important ‘enlightment’ moments is that the function call tell you exactly what to expect without looking back at how it was declared. It is strict by design so that you cannot screw it up.

Imagine, you are writing a black-box email sending class and you need to tell other programmers how to use it by telling them the name of the functions, the parameters they accept. Ask yourself, how did you do it in PHP/Javascript/Ruby? For me, it would be via the source code or the documentation.

In Objective-C this mechanism is built right into the function name itself. Even if you don’t have the source code or the documentation, you still can pretty much understand how to use it correctly. The parameter names are always self-descriptive and the type is strict. Again, you cannot use the wrong syntax, the compiler will simply cough out tons of red lines and refuse to let you do any more stupid things.

So in my opinion, this is actually brilliant design. No doubt it requires more typing, but it potentially saves a lot of (human) communication errors when sharing codes and working in a team. When I was still coding in PHP, I found myself constantly having another file open just see the declaration of a function I wrote before that. (Extra typing time * 100000) < Total time save ==> happy coder.

If you are not convinced

do_send_email("[email protected]", "[email protected]", "Hello!", "hi!");

Now, which one is the recipient? What is the subject?

[emailSender doSendEmailToRecipient:@"[email protected]"
                                 cc:"[email protected]"

Crystal clear!

I hope you understood the very fundamental reason why Objective-C syntax has to be the way it is. Accept the ‘weird’ syntax that you have never seen before, and appreciate the thoughts Apple has put into improving the language (Apple does not design it) and be at peace with yourself.

Updated: as pointed out by one commenter below. The language was designed by Brad Cox, not Apple. Apple inherited it with OpenStep/Rhapsody/MacOSX.

Let me know what you think about this post and give me some feedback on what should I write next for the series in the comment form below.

The iOS Beginner blog series

Posted: January 14th, 2012 | Author: | Filed under: iOS | Tags: , , , , | 17 Comments »
This entry is part 1 of 4 in the series iOS Beginner blog series

A dedication to the high-level programmers

After almost a year learning Objective C and iOS programming, now I can say that I understand most of the materials available in StackOverflow and there is rarely any question that I don’t know *how* to look for the answer. I can certainly tell the differences between a .h file and .m file and I also know how to load up cool stuffs from cocoacontrols.com and see if I can use them for my needs.

However, looking back at the early days, none of the above made any sense to me at all. I blamed myself mostly for having absolutely no background in any low level language. No C, C++, Pascal, etc. Like many developers out there, I started since very young with self-taught front-end web programming skills (HTML, CSS, JS) then moved on to back-end languages like PHP. (I started Rails at the same time as Objective C too).


The problem with having such a long history with web programming languages is that all languages fundamentally are the same: no compilation, no machine code, real time changes, nothing to do with memory management. For me coding = write code, refresh, see, change, refresh

And so, I threw myself into iOS with a very open mind, expect the unexpected, just like any other time I prepared to dive into new platforms. But this time, it’s not like any other. For the first month I really struggled, trying to convince myself to learn, trying not to give up and pull out. App crashed almost every time I tried to run, or worse, it didn’t even compile and I have no clue where or what to fix. I just couldn’t accept the fact that I have to write so much code just to achieve so little.

It took me a really long time to put a single HelloWorld on the screen because trying to find the answer for one question only lead to many others:

Begin: How do I write a Hello World on the screen?
=> What type of project should I start Tabbed Application or Single View Application or Utility Application (XCode template)?
=> What’s a window? What’s a controller? Why is it called a view-controller, not view *and* controller?
=> What’s the function to create a label?
=> Where the f**k are the function’s parameters?
=> How to put a label in the correct position?

And then there’s all the nasty provisioning before I can gulp in the delicious HelloWorld word on my iPhone. Don’t even start asking.


I kept bitching and complaining how much more work it was compare to Rails for several months (most of the time to my colleagues @ajhit406, @arun). Only when I started to accept the fact that Objective-C is a compiled, low-level language, in which my experience was clearly absent, I began to appreciate the language and the way the whole eco-system works. I no longer view [[alloc] init] as chores, instead, I remember every one of them and consider how much memory it might take everytime I wrote it.

Not only I learnt how to write Objective-C codes, the process of creating apps taught me so much more about designing for small screens. And that is why whenever I got a chance, I wouldn’t stop cursing and swearing about how bad Android design is and how fundamentally broken it is.

So I hope you got the point clear, if not : Objective-C is an awesome language. Period.

iOS Beginner blog series

With that, I wanted to help out those who began to learn iOS development, especially programmers who are coming from no programming background or web development background, to quickly adapt to Objective C and understand the broader picture.

The iOS Beginner blog series, including this one will attempt to do that.
The series will not to teach you how to achieve specific implementations, however, my approach will be to explain the fundamental concepts, the “why” of why you have to do certain things.

It took me only a month from a total noob to be doing advanced Rails stuff. But it took me almost a year to be confident in making good quality iOS apps, for example this one. So I hope by sharing my experience, you won’t take as long.

The very first concept will be from one of the questions above, which I found most difficult to understand at first: Where the f**k are parameters?

A replica of Path’s table view

Posted: January 13th, 2012 | Author: | Filed under: Custom UI, iOS | 5 Comments »

If you have used Path recently, then the screenshots above should be very familiar. I am always very keen on learning about new ways of providing better user experience through interface design so Path 2.0 impressed me a lot in that area. There are several innovative UI controls in just one single app. The most noticable one was the fly-out menu. It has been replicated in Objective-C, CSS3 and even Adobe Edge.

So for the hackathon night at Anideo, I decided to replica and create a flexible foundation for another not less impressive control found in Path App : the overlay info panel that shows time when you scroll.

The screenshots above shows my progress so far after a few hours into it. It works pretty well with relatively little code. Download demo video of it in action here demo.mov (1.1MB)

The implementation I wanted has to be simple and flexible. Built with just a simple UIView for the overlay and a UIImage stretched to fill the background. It is highly customizable with 6 callback events that you can override to provide any functionality that you need.

I have push the code to my public git repo at https://github.com/kentnguyen/KNPathTableViewController
You can get the code and run the Demo project to get an idea what you can do with it or follow my code below.

How to use and extend KNPathTableViewController

First, the library consists of two source files and two graphic files for the background. Add these files to your XCode project as usual. Everything you need to know about this class can be found in .h file.

Create your own class based on KNPathTableViewController and use it like a normal UITableViewController out of the box. At this moment, only two init methods are supported, but you can submit a pull request to my repo and add more if you need to.

-(id)initWithStyle:(UITableViewStyle)style infoPanelSize:(CGSize)size;

The infoPanelSize is the width and height of your overlay control. The background is created using UIImageView with a stretchable image based on the midpoints of the two images. Default size and other settings can be changed in .h as well.

After you have declared your custom class, override these methods in your implementations

-(void)infoPanelDidScroll:(UIScrollView*)scrollView atPoint:(CGPoint)point;

All of these are optional but the most important one you should override is the infoPanelDidScroll:atPoint: call.

The overlay info panel UIView can be access using read-only property self.infoPanel and you can use this to add your custom elements.

In my Basic Demo, I added a single UILabel to the overlay and update it with the information about the current row it is at. The current row index can be calculated with the (CGPoint)point parameter.

In Path App, there is a lot more than just a simple UILabel: a round background clock, two moving clock hands, two dynamically sized labels that show date and time. Essentially they are additional information about the current postion it is at. And it is not limited to that single row as you can see in my Section Demo. The overlay label shows the current section it is at.


So from here, the possibilities are quite unlimited. You can use this control as another space-saving tool for the important-but-tiny tableview. You can potentially do away with the section headers and display it in the overlay instead. Alternatively, you can just use it as a fancy touch to your app. Up to you.

I do not have any future plan for the library but you could suggest more using the form below.
Also, let me know if you use it in any of your cool project.

Oh and checkout my other app too.


Posted: January 1st, 2012 | Author: | Filed under: Personal | No Comments »

A few years ago when I was searching for my own domain, I found this domain but after a few hours trying to borrow a creditcard (I didn’t have one then), the domain was already bought by the f**king stupid networksolutions.com I used to check for availability. I didn’t want to be ripped off by higher price and bought nguyenkent.com instead.

Two days ago, I was reviewing my domains and something reminded me of it so I tried my luck. And here it is, my own KentNguyen.com that I have always been waiting for.

So as part of my new year resolutions, I needed to start a tech blog and begin sharing experience in my work and interesting skills I picked up over the years. A few people are sure very eager to read what I have to share. But mainly I just wanted to see if I can increase my presence and back links to my profile online.

For the start, if you haven’t known who I am already, head to my About Me page and see if you can spot anything unusual.

The cool thing about this blog is that it serves iPad differently and iPhone differently as well. Check it our for yourself.