Monday 24 March 2014


Saturday 22 March 2014




The App Launch Sequence on iOS


Apple made some changes to the app launch sequence in the default project templates in Xcode 4.2. For that reason, I revisited this topic in a new article. Please refer to the new post for up-to-date information.
I noticed that many beginning iOS developers see the launch process of an iOS app as a bit of a mystery. Somehow, someone sends our application delegate an application:didFinishLaunchingWithOptions: message, seemingly the first place where we have chance to inject code of our own. But how does our app get there?

In the beginning was main()

The execution of every C program starts with a function called main(), and since Objective-C is a strict superset of C, the same must be true for an Objective-C program. If you create a new iOS project from one of the default templates, Xcode places this function in a separate file called main.m in the Supporting Files group. Usually, you never have to look at that file but let’s do. This is the entire code of main():
int main(int argc, char *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;

}
The function’s arguments argc and argv contain info about the command-line arguments passed to the executable on launch. We can safely ignore them for this discussion. Let’s have a look at what the function does, which seems to be very litte:
  1. It creates an autorelease pool because in every Cocoa app one must exist at all times (otherwise, an autorelease call would fail).
  2. It calls a function named UIApplicationMain(). We will take a deeper look at it below.
  3. It drains the autorelease pool it just created.
  4. It returns the return value of UIApplicationMain() to its caller (which is the shell that launched the executable).
When an (Objective-)C program reaches the end of main(), it ends. So this looks like a very short program indeed. Nevertheless, this is how all iOS apps work, so the secret must be the UIApplicationMain() function. Should it ever return, our program would end immediately.

UIApplicationMain()

Looking at the documentation for UIApplicationMain(), we find this:
This function instantiates the application object from the principal class and and instantiates the delegate (if any) from the given class and sets the delegate for the application. It also sets up the main event loop, including the application’s run loop, and begins processing events. If the application’s Info.plist file specifies a main nib file to be loaded, by including the NSMainNibFile key and a valid nib file name for the value, this function loads that nib file.
Despite the declared return type, this function never returns.
Let’s take this apart step by step:
App Launch Sequence on iOS 4
Flowchart of the app launch sequence on iOS 4. Feel free to share this image under a Creative Commons Attribution license (CC-BY).
  1. First, the function creates the main application object (step 3 in the flowchart). If you specify nil as the third argument to UIApplicationMain() (the default), it will create an instance of UIApplication in this step. This is usually what you want. However, if you need to subclass UIApplication (for example, to override its event handling in sendEvent:), you have to pass a string with the name of your subclass to UIApplicationMain().
  2. The function then looks at its fourth argument. If it is non-nil, it interprets it as the name of the class for the application delegate, instantiates an object of this class and assigns it as the application object’s delegate. The default for the fourth argument is nil, though, which signifies that the app delegate will be created in the main NIB file.
  3. Next, UIApplicationMain() loads and parses your app’s Info.plist (step 4). If it contains a key named “Main nib file base name” (NSMainNibFile), the function will also load the NIB file specified there (step 5).
  4. By default, the main NIB file is called MainWindow.nib. It contains at least an object representing the application delegate, connected to the File’s Owner’s delegate outlet (step 6), and a UIWindow object that will be used as the app’s main window, connected to an outlet of the app delegate. If you used a view-controller-based app template, the NIB file will also contain your app’s root view controller and possibly one or more view child controllers.
    It is worth mentioning that this is the only step where the UIKit-based app templates (Window-based, View-based, Navigation-based, Tab-based, etc.) differ significantly from each other. If you started out with a view-based app and later want to introduce a navigation controller, there is no need to start a new project: simply replace the root view controller in the main NIB file and adjust one or two lines of code in the app delegate. I noticed that many newbies to the iOS platform struggle with this problem and assume a huge difference between the different project templates. There isn’t.
  5. Now, UIApplicationMain() creates the application’s run loop that is used by the UIApplication instance to process events such as touches or network events (step 7). The run loop is basically an infinite loop that causes UIApplicationMain() to never return.
  6. Before the application object processes the first event, it finally sends the well-known application:didFinishLaunchingWithOptions: message to its delegate, giving us the chance to do our own setup (step 8). The least we have to do here is put our main window on the screen by sending it a makeKeyAndVisible message.

Entry points

You see, there is no magic here. Besides application:didFinishLaunchingWithOptions:, there are several more entry points for custom code during the launch sequence (none of which are usually needed):
  • Directly in main() before UIApplicationMain() is called.
  • The init method of a custom UIApplication subclass.
  • The initWithCoder: or awakeFromNib methods of our application delegate if it is created from a NIB file (the default).
  • The +initialize methods of our application delegate class or a custom UIApplication subclass. Any class receives an +initialize message before it is sent its first message from within the program.
Note that this sequence only happens at the actual launch of an app. If the app is already running and simply brought back from the background, none of this occurs.


I have followed original blog post : http://oleb.net/blog/2011/06/app-launch-sequence-ios/

Wednesday 19 March 2014

Useful Obj-C Snippets for iOS Apps:

As an iOS developer, I keep a shed-load of Objective-C snippets nearby whenever I’m coding that I often refer to and copy into my apps. There are so many commonly employed elements in an iOS app that it is just about impossible to remember them all. In this article, I share my favorites, those that I reach for the most. Some are longer than others, but they are all invaluable to any iPhone or iPad developer.
One great way to make use of these snippets is to assign them to short keywords in an app like TextExpander, speeding up your app development significantly.

Open a URL in Safari

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com/"]];

Dial a Number

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://9662256888"]];
Dial a Number
Dial a Number

Launch Mail and Send an Email

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://mymail@myserver.com"]];

Prevent Sleep Mode

[UIApplication sharedApplication].idleTimerDisabled = YES;

Stop Responding to Touches

[[UIApplication sharedApplication] beginIgnoringInteractionEvents];

Resume Responding to Touches

[[UIApplication sharedApplication] endIgnoringInteractionEvents];

Display an Alert Window

UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"too many alerts" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alert show]

Display the Name of your Application

self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];

Change the Style of a Navigation Bar

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];

Get the Current Date and Time

NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];

Make a Vibration

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

Display the Number of Launches

NSUserDefaults *countDefaults;
int launchCount;

countDefaults = [NSUserDefaults standardUserDefaults];
launchCount = [countDefaults integerForKey:@"launchCount" ] + 1;
[countDefaults setInteger:launchCount forKey:@"launchCount"];
[countDefaults synchronize];


NSLog(@"Launch number: %i", launchCount);
Console Log of Launch Number
Console Log of Launch Number

Configuring a UIScrollView

[scrollView setScrollEnabled:YES];
[scrollView setContentSize:CGSizeMake(320, 1400)];

Set Title of a View in a UIViewController

viewController.title = @"Title Here...";
Navigation Bar Title
Navigation Bar Title

Set the Font and Size of a UITextView

[thankYouTextView setFont:[UIFont fontWithName:@"Helvetica" size:16]];

Set the Font Size of a UILabel

[textView setFont:[UIFont fontWithName:@"Helvetica" size:16]];

Presenting a UIViewController

ViewController *viewController = [[ViewController alloc] init];
viewController = @"Title Here...";
[self.navigationController viewController animated:YES];

Hiding the Back Button in a Navigation Controller

self.navigationItem.hidesBackButton = YES;

Set Background of View

self.view.backgroundColor = [UIColor colorWithHue:1.0 saturation:0.0 brightness:0.6 alpha:1.0];

Give App Icon a Badge Number

[UIApplication sharedApplication].applicationIconBadgeNumber = 10;

Align UILabel Text

titleLabel.textAlignment = UITextAlignmentCenter;

Set Background of Tab Bar

UIImage *tabBarBackground = [UIImage imageNamed:@"TabBarOverlay.png"];
[rootController.tabBar setBackgroundImage:tabBarBackground];

Have you got some favorite snippets you find yourself reaching for constantly that haven’t been included on the list? Tell us about them in the comments!


Friday 14 March 2014

Objective-C Math functions :

Objective-C uses C’s math which you can find in math.h, however as we do program in different languages it is really annoying to remember by heart how the function names are abbreviated in each and every language. Thus comes here a short math overview of the math in Objective-C.



Math functions :

double pow ( double, double ) - power of

NSLog(@"%.f", pow(3,2) ); //result 9
NSLog(@"%.f", pow(3,3) ); //result 27

double  sqrt( double ) - square root

NSLog(@"%.f", sqrt(16) ); //result 4
NSLog(@"%.f", sqrt(81) ); //result 9 

double ceil ( double ) : - if the argument has any decimal part, returns the next bigger integer

NSLog(@"res: %.f", ceil(3.000000000001)); //result 4
NSLog(@"res: %.f", ceil(3.00)); //result 3

double floor ( double ) - removes the decimal part of the argument

NSLog(@"res: %.f", floor(3.000000000001)); //result 3
NSLog(@"res: %.f", floor(3.9999999)); //result 3

double round ( double ) - rounds the argument

NSLog(@"res: %.f", round(3.5)); //result 4
NSLog(@"res: %.f", round(3.46)); //result 3
NSLog(@"res: %.f", round(-3.5)); //NB: this one returns -4

double fmin ( double, double ) - returns the smaller argument

NSLog(@"res: %.f", fmin(5,10)); //result 5

double fmax ( double, double ) - returns the bigger argument

NSLog(@"res: %.f", fmax(5,10)); //result 10

double  fabs( double ) - returns the absolute value of the argument

NSLog(@"res: %.f", fabs(10)); //result 10
NSLog(@"res: %.f", fabs(-10)); //result 10
 
Eventually you will find also all the trigonometry you’ll need as: sin, cos, tan, atan, and their variations.

Few math constants

As found in the math.h
#define M_E         2.71828182845904523536028747135266250   /* e */
#define M_LOG2E     1.44269504088896340735992468100189214   /* log 2e */
#define M_LOG10E    0.434294481903251827651128918916605082  /* log 10e */
#define M_LN2       0.693147180559945309417232121458176568  /* log e2 */
#define M_LN10      2.30258509299404568401799145468436421   /* log e10 */
#define M_PI        3.14159265358979323846264338327950288   /* pi */
#define M_PI_2      1.57079632679489661923132169163975144   /* pi/2 */
#define M_PI_4      0.785398163397448309615660845819875721  /* pi/4 */
#define M_1_PI      0.318309886183790671537767526745028724  /* 1/pi */
#define M_2_PI      0.636619772367581343075535053490057448  /* 2/pi */
#define M_2_SQRTPI  1.12837916709551257389615890312154517   /* 2/sqrt(pi) */
#define M_SQRT2     1.41421356237309504880168872420969808   /* sqrt(2) */
#define M_SQRT1_2   0.707106781186547524400844362104849039  /* 1/sqrt(2) */
 
#define MAXFLOAT ((float)3.40282346638528860e+38)
 
 
So, this is a wrap up for the overview of Objective-C math, if I missed the one function you use the most, feel free to leave a comment and share it with the other readers.

Original blog post is Here : http://www.touch-code-magazine.com/objective-c-math-functions/