Wednesday, October 19, 2011

Coding - Flow Like a River

I thought I write about how newbies tend to copy and paste codes to make things work. I admit copy and paste is the easy way to learn coding. I do it at times as well. But in the end, programming/coding is about how an app FLOW. The flow of an app is very crucial for every newbie developer to grasp.

Often I read programming forums there are people who post codes and asking why it does not work. And you know immediately that they are just copying blindly since they don't even know what each line does and how the code flows in the app.

Every app, or programs, or executables, (whatever you want to call them), have a flow of executions. It is like reading a book, you read the title, first paragraph, next paragraph, page 1, page 2.. and so on. iPhone apps are no different. In an iPhone app, you have the main.h (yes we ignore that file and some don't even know it exists!) which calls the AppDelegate, and the AppDelegate calls the ViewController. To simplify, lets skip direct to the AppDelegate.

THE FLOW of an iPHONE APP

1. AppDelegates is called - applicationDidFinishLaunching is executed. In this method normally we directly call the first viewController (say FirstViewController) to appear after the Launch image is shown.

2. Next thing that happens, of course, is the codes inside the function "viewDidLoad" in FirstViewController.m.
Normally in this method you can put initialization of the view (for eg, buttons location, hidden/not, start a timer and so on)

3. Then from here, everything is based on user's input (or timer's action if there is a timer).

4. App Exit / Goes to background.

This is a simple flow, but many people do not realize this. Even in each of the user's actions there are flow of their own. You, as developer need to cater for every single line of codes. If you want to use a variable, you must check what is the contents of that variable. Has it been loaded with values? Has it been initialized even?
There is no point to read a variable into a UILabel, if you haven't loaded any values in it!

For eg,

in .h
NSString *myStr;


in.m (IBAction)userPressButton

myLabel.text = myStr;


This won't work. You need to load/init the myStr with something first (for eg, in the viewDidLoad!)

in .m (void)viewDidLoad

myStr = [NSString stringWithFormat:@"%@",[ [NSUserDefaults standardUserDefaults] objectForKey:@"storedString"]];

Then when user press the button, myLabel.text will show a value and it works.

These are the FLOW of apps, and of functions/methods and all developers should know how a user use their apps and what to do if a user acted.

I hope this post has been useful.