Apples iOS4 update What’s in it for the developers

Last week at Apples World Wide Developer Conference Steve Jobs unveiled iPhone OS’s yearly major upgrade, introducing a plethora of new functionality. In this post we will try to touch the tip of iceberg in terms of what iOS4 has to offer to the developers.

The first thing you’ll notice about iPhoneOS is that it has been renamed to iOS basically because now it runs on iPads, iPhones & iPod touches & iOS is somewhat a generic name.

Below is the description of new features in the iOS from the developer’s point of view.

Multitasking

The first and foremost thing that catches the attention of developers is the ability of iOS4 to multitask. Multitasking is not a new feature in mobile computing, Palm’s WebOS, Google’s Android & even Microsoft’s Windows Mobile have multi-tasking capabilities. Multitasking application lifecycle is a little different than the traditional application lifecycle that we were used to in Cocoa touch. Apples multitasking implementation is somewhat similar to that of Google’s on the Android platform. Which is in-fact not true multitasking just a mere illusion of multitasking.

When the user wants to switch to another application the state of application is saved or frozen in the memory and when the user gets back to the application the state of application is restored giving an illusion that application was running all along.

When the application is inactive it is barred from any processing except if the application has registered as one of the following

  • Location (GPS related)
  • Audio
  • VoIP (Voice over IP)

This is how application state is specified in the UIApplication.h header file

typedef enum {

UIApplicationStateActive,

UIApplicationStateInactive,

UIApplicationStateInBackground

} UIApplicationState;

Illustrating that we have three application states on the iOS4.

  • Active
  • Inactive
  • In Background

When the application is launched we will receive the usual message from the app delegate

- (void)applicationDidFinishLaunching:(UIApplication *)application

didfinishLaunchingWithOptions(NSDictionary *)launchOptions

In addition to this we will now also receive this message

-   (void)applicationDidBecomeActive:(UIApplication *)application

When going to the background we will receive these messages

- (void)applicationWillResignActive:(UIApplication *)application

- (void)applicationDidEnterBackground:(UIApplication *)application

When in background there are no guarantees that the app will remain in the memory for the entire eternity. If there is a OOM(Out Of Memory) call the runtime will kill our application & free some memory.

When our application comes back to foreground these two methods will be called by the app delegate.

- (void)applicationWillEnterForeground:(UIApplication *)application

- (void)applicationDidBecomeActive:(UIApplication *)application

We can implement our logic in these two delegates; like connecting to the server again or whatever the logic of our application demands.

iOS4 also gives us the functionality to ask for a little more time for processing when the application is being suspended so that we can save state or finish the job for that matter before getting suspended. These are the two calls we can use to tailor our app to our requirements.

-   (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler: (void(^)(void))handler;

-   (void)endBackgroundTask:(UIBackgroundTaskIdentifier)identifier;

*Notice the weird looking syntax (void(^)(void)), this is known as a block & is a recent addition to the C, C++, Objective C & objective C++ by Apple & is abundantly used in many Foundation classes so understanding it is very crucial, more on it later.

Local Notifications

A new feature in iOS4 is of local notification system, this feature somewhat mimics the Apples Push Notification System but is local to the device. Any application can register for notifications locally on the device & the device can then send periodic updates as specified or can change the application badge or do all of the stuff that was possible with Push Notification System. For more information on Local Notification be sure to check out the UILocalNotification.h header file.

UIAutomation

UIAutomation is a new framework that Apple has introduced with the iOS4 SDK. Now you can write Javascript based scripts to automate user testing & check your application rigorously. You can run your scripts along with all the performance tracking systems included in the SDK like Instruments or Shark.

Event Kit

Enables the developers to access the calendar of the user on the device, so that the developer can create, edit, remove & search events on the calendar locally & or any online calendars users are using. Developers will also be able to record change notifications for the events on the calendar.

iAd

iAd is Apples advertising framework, developers can use iAds for loading & presenting ads. Apple also enables developers to respond to the events in ads. One plus point of iAd is that when you tap on the ad in the application, the application will not exit to show you the ad in Safari, you will remain in the application & you can close the ad anytime you want. This is one big convenience when compared with other ad offering frameworks like Google’s Ad-Mob.

Game Center

Is a social networking gamming system something like OpenFeint. Now you can view achievements, compare them with your friends, view leader boards, find new games etc all of the stuff which you were able to do with OpenFeint is now possible with Game Center.

Core Motion

In addition to the accelerometer Apple has added the gyroscope to the iPhone 4. Now you can use the API in the Core Motion to take advantage of gyroscope & make your applications more interactive.

Core Foundation & Foundation additions

CF & NSFoundation has been brought to the snow leopard equivalence in iOS4, which includes the inclusion of Blocks & Regular Expressions to name a few.

Blocks

Here is a small introduction to Blocks to get your feet wet.

Blocks are self-contained units of work; they are similar to but far more powerful than traditional function pointers. Blocks are objects & they respond to NSObject methods. Here is a small example on blocks to get you started:-

Declaring a block variable:

void (^my_block)(void)); //first void is return type (^my_block) is the block declaration & the other void is the argument in the argument list.
Assigning a block object to it:

my_block = ^(void){ printf("hello world\n"); };
Invoking it:

my_block(); // prints “hello world\n”
Accepting a block as an argument:

- (void)doSomething:(void (^)(void))block;
Using that method with an inline block:

[obj doSomeThing:^(void){ printf(“block was called”); }];

Google’s Go Programming Language

Google’s New Programming Language GO

Introduction.

In this blog post we will go through the installation of the Go programming language tool-chain on Linux & most probably talk about the basic programming constructs of this language.

I am using an Intel Core 2 Duo processor and Linux flavor is Ubuntu 9.10 code named Karmic Koala.

The official installation procedure can be found at http://golang.org/doc/install.html. We will be following the same procedure but I will be explaining few of the steps in between so that you don’t get lost.

Step 1. Setting Environment Variables

First thing we need to do is to set the environment variables in .bashrc in your home directory. You can read more about bash & .bashrc at http://en.wikipedia.org/wiki/Bash#Startup_scripts.

On your Linux desktop go to the Applications menu → Accessories → Terminal. This will bring up the terminal. Type “cd ~” & hit enter to make sure you are in your home directory.

Now type gedit .bashrc in the terminal.

This will open up the .bashrc file in gedit, scroll down to the end add the following text

# Environment variables for Go programming language.

export GOROOT=$HOME/go

export GOOS=linux

export GOARCH=386

export GOBIN=$HOME/bin

Save file & close the document. Type exit in the terminal to exit. Once again go back to the application menu and click on the terminal by following the route specified above.

Type env | grep ‘^GO’ to check environment variables are set correctly.

If everything went well you will see something like this

click to enlarge

Installing Mercurial

Once you the environment variables are set correctly type

sudo apt-get install mercurial

The package if not installed will be downloaded & installed or upgraded depending upon your system.

Screenshot
click to enlarge

You can read more about mercurial here: http://en.wikipedia.org/wiki/Mercurial

Checking Out From The Repositories

Once mercurial is installed type the following command on the terminal to checkout the latest code from repositories

hg clone -r release https://go.googlecode.com/hg/ $GOROOT

Wait for a while until it gets downloaded

Installing Other Required Components

On getting the prompt back type

sudo apt-get install bison gcc libc6-dev ed

If the above-mentioned programs are not installed on your system they will be downloaded and installed.

Installing Go

Once you get the prompt back & above mentioned programs are successfully installed on your system, type:

cd $GOROOT/src

And then enter the following command

./all.bash

Installation process will begin & if all goes well you will see screen like this.

Screenshot-2
click to enlarge

Congratulations you have successfully installed the Go language tool-chain, now its time to get our hands dirty with a little programming.

Hello World in Go

Now type:

cd ~

to go to the home directory now create a new folder by typing

mkdir google-go

type:

cd google-go

to go to the newly created directory.

Now type:

Gedit

& hit enter

Enter the following code in gedit.

Example 1

package main

import fmt “fmt”

func main(){

fmt.Printf(“Hello World from Go programming language\n”)

}

That’s it, save the document as hello.go and exit the gedit.

On the terminal type:

8g hello.g

to compile the source. If all goes well you’ll get to the prompt with anything showing.

Now type 8l hello.8 (thats character ‘l’ after 8 not numeric 1), this command will link the required libraries “fmt “ in our case which imported in our program.

And to run the program type ./8.out

Congratulations you have compiled your first program in Google’s new programming language Go. Be proud of yourself.

Try changing this program use different language constructs. Below is the yet again a simple program which will get you started. I cannot go over every language construct so feel free to visit the official Go website. You’ll grasp the concepts very quickly if you have any prior programming experience.

Example 2

package main

import fmt “fmt”

func main(){

var i int = 1;

var stng string;

var j [10]int;

stng = “A string”;

fmt.Printf(“The String contains : %s, integer contains : %d, and array %i \n”, stng , i, j);

for k := 0; k<10; k++{

fmt.Printf(“%d Checking for loop\n”, k);

}

}

You should have noticed that Go is a C based language & C/C++ programmer will have no trouble using this language.

Below is one hour Google Tech Talk video hope you will enjoy it.

You can always visit the official website http://golang.org/ to learn more.

Philosophy of Make

Introduction.

In this blog post I will try to explain to you the anatomy of a typical make file, as most of the new comers to Unix/Linux arena often find it difficult comprehend the philosophy behind the make & they often do get imitated by its weird looking syntax and structure. We’ll first describe why a make is needed and then I will highlight the basic structure and syntax of a make file and will then we will wrap up the post by presenting some examples to make your concepts clear.

The case for make

Make is a tool that is used to control the build process of your software.

Make automates what is built, how it gets built, when it gets built etc. A makefile is a place where you store all of your commands to build the software.

Similar concept exists in the Java world in shape of Ant and more recently Maven that even provide more functionality and flexibility to compile, test & even deploy your applications through simple xml files.

Suppose you have multiple source files that require long & complex compiler invocations, “make” simplifies this by storing these commands in a single makefile so that they can be managed from a single location. You can also specify which files & directories you want create and delete based upon certain circumstances. Like for example you want all your library files to be compiled into the lib folder of the installation directory. “Make” also makes it easier for other people who want to compile and execute your application; in place of creating huge documentation on how to build your software you can just tell them to run make & it would take care of the rest.

Finally as the final argument in favor of make I think it really speeds up the build process of your application. Make is intelligent enough to recognize which files have changed and thus only builds those files whose components have changed. Plus makefiles also constitute a database of dependency information allowing you to automatically verify that all the files for the build are present.

Anatomy of a MakeFile

A make file is a simple text file containing rules that tell make what to build and how to build it. A makefile consists of number of rules, at its basic the general structure of make looks likes this:-

# Comments use the hash symbol

Target : dependency [dependency] [ … ]

Command 1

Command

Command n

Target is what we are trying to build a binary or an object file. Dependency is a list of one or more files required for the compilation, commands are the steps either compiler invocations or shell scripts required to create the target.

The spaces before commands are TABS & should be used as such, empty spaces would not suffice in their place & you would get the missing separator error. This is the most common problem people new to make get stucked with.

Example of a Make File

edit : main.o kbd.o command.o display.o \

insert.o search.o files.o utils.o

cc -o edit main.o kbd.o command.o display.o \

insert.o search.o files.o utils.o

main.o : main.c defs.h
              cc -c main.c
kbd.o : kbd.c defs.h command.h
              cc -c kbd.c
command.o : command.c defs.h command.h
              cc -c command.c
display.o : display.c defs.h buffer.h
              cc -c display.c
insert.o : insert.c defs.h buffer.h
              cc -c insert.c
search.o : search.c defs.h buffer.h
              cc -c search.c
files.o : files.c defs.h buffer.h command.h
              cc -c files.c
utils.o : utils.c defs.h
              cc -c utils.c
clean :
      rm edit main.o kbd.o command.o display.o \                               
      insert.o search.o files.o utils.o

Two long lines are split into two by using backslash-newline. This make file will create an executable “edit”.

To compile the program simply just type make on the command prompt.

This make file has 10 rules. The first target edit is the default target which is the binary we are trying to create. Edit has eight dependencies from main.o to utils.o, all of these files must exist to create the edit binary. The next line is the command that make executes to actually create the binary. Here make would actually build the executable from all these object files that are named .o.

When make encounters a dependency and it does not exists make executes the command to build it & if the dependency has further dependencies make tries to find them & if they does not exist make tries to build them using the command specified and so likewise make is able to traverse through all of the dependencies if present and build the software smoothly.

Clean target as you can see is the simple command that removes all the object files and as well as the final binary using the rm command.

Phony Targets

A phony target is one that is not really the name of a file. It is just a name for some commands to be executed when you make an explicit request. There are two reasons to use a phony target: to avoid a conflict with a file of the same name, and to improve performance.

Like for example there is a file named clean it would be disregarded by make. Phony targets are defined like this in a make file for example

.PHONY : clean zip

rm abc.o xyz

zip : clean

zip abc.zip *.c *.h Makefile

There are a lot of command line arguments that make can take the following is a short list of useful command options.

-f file                         Read the file name file instead of standard names

-n                         Display the commands make would executes without actually executing them

-s                        Execute silently ie not printing the commands make executes

-w                        print directory names when make changes directory

-r                         disable all of makes built-in rules.

-d                         print lots of debugging information

-k                         keep executing even if one target fails to build.

-jN                        Run N commands in parallel, where n is an non-zero integer.

More exhaustive list can be found at http://www.gnu.org/software/make/manual/make.html#Options-Summary

Variables

To simplify editing and maintenance make allows us to use variables. There are four kinds of variables

  1. User defined variables
  2. Environment variables
  3. Automatic variables and
  4. Pre-defined variables

User-Defined Variables

We define variables using the general form:

VARNAME = value [ … ]

It is a convention to use upper case letters for variables names, to obtain a variables value we just parenthesize the variable and add a dollar sign as a prefix.

There are two kinds of variables in “make” simply expanded variables and recursively expanded variables. Recursively expanded variables as the name suggest expands variables within variables until there are no further variables. For example

HOME_DIR = /home/asad

DEV_DIR = $(HOME-DIR)/development

PROJ_DIR = $(HOME-DIR)$(DEV-DIR)/project

SRC_DIR = $(HOME-DIR)$(DEV-DIR)$(PROJ_DIR)/src

If you use SRC_DIR variable somewhere all of the variables would get expanded.

Simply expanded variables are scanned once where they are defined and all embedded variable references are immediately resolved. Syntax is slightly different

CC := gcc

CC += -g

This would result in gcc –g when resolved.

If you consider using recursively expanded variables for this for example

CC = gcc

CC = $(CC) – g

We would get stuck in an infinite loop as $(CC) would keep on getting resolved to the same expression $(CC) & make would throw an error.

Environment Variables

Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. $(HOME) variable for example can be used in make to refer to the users home directory.

Automatic Variables

Automatic variables are those variables whose value is evaluated each time a rule is executed, based on target and dependencies of that rule. Automatic variables are used to create pattern rules, patterns are generic instructions on how to compile an arbitrary .c file to its corresponding .o file.

Here is a partial list of automatic variables

$@                        The file name of the target of the rule.

$<                        The name of the first prerequisite/dependency.

$?                        The names of all the prerequisites that are newer than the target, with spaces between them.

$*                         The basename (or stem) of a filename.

$^                        Expands to a space-delimited list of all of a rules depedencies.

$(@D)                        The directory part of targets path name, if named target is in the sub-directory.

$(@F)                        The file part of targets path name, if named target is in the sub-directory.

For an exhaustive list please visit

http://www.gnu.org/software/make/manual/make.html#Automatic-Variables

example:

CFLAGS := -g

CC := gcc

.c .o:

$(CC) $CFLAGS –c $* .c

lock: lock.c

$(CC) $(CFLAGS) $< -o $@

for each filename ending in .c make would create an object file ending with .o, while executing $< would be replace with lock.c similarly target name $@ will be replaced by lock.

Pre-Defined Variables

These are the variables that as the name suggests are predefined by make. A few of them are listed below.

AR                        Archive-maintaining program; default `ar’.

AS                        Program for compiling assembly files; default `as’.

CC                        Program for compiling C programs; default `cc’.

CO                        Program for checking out files from RCS; default `co’.

CXX                        Program for compiling C++ programs; default `g++’.

CO                         Program for extracting a file from RCS; default `co’.

CPP                        Program for running the C preprocessor, with results to standard output; default `$(CC) -E’.

RM                        Command to remove a file; default `rm -f’.

ARFLAGS            Flags to give the archive-maintaining program; default `rv’.

ASFLAGS            Extra flags to give to the assembler (when explicitly invoked on a `.s’ or `.S’ file).

CFLAGS            Extra flags to give to the C compiler.

For an exhaustive list please see

http://www.gnu.org/software/make/manual/make.html#Implicit-Variables

Conditional Statements

Conditional expressions can be applied to a make file so that parts of make file execute or not based on certain conditions. Generic syntax is as follows

conditional-directive

text-if-true

else

text-if-false

endif

The following example of a conditional tells make to use one set of libraries if the CC variable is `gcc’, and a different set of libraries otherwise. It works by controlling which of two command lines will be used as the command for a rule. The result is that `CC=gcc’ as an argument to make changes not only which compiler is used but also which libraries are linked.

libs_for_gcc = -lgnu

normal_libs =

foo: $(objects)

ifeq ($(CC),gcc)

$(CC) -o foo $(objects) $(libs_for_gcc)

else

$(CC) -o foo $(objects) $(normal_libs)

endif

This conditional uses three directives: one ifeq, one else and one endif.

Last Example

In the last example I would like to show you how to create install, dist and uninstall targets that you can most probably use while distributing your applications.

Hello: hello.c

install : hello

install $< $(HOME)

.PHONY : dist unistall

dist :

$(RM) hello *.o core

tar czvf hello.tar.gz hello.c Makefile

uninstall:

$(RM) $(HOME)/hello

and you can use make install, make dist & make uninstall commands for respective functions.

With this I think we should wrap up our tutorial on make. This is not a fully exhaustive tutorial but it would place you on the right grounds & will get you started with make hopefully. If you have any questions please don’t hesitate to ask and If you want to know more about specific details & I don’t impress you much you can always access the online documentation at http://www.gnu.org/software/make/manual/.