Showing posts with label multi threading. Show all posts
Showing posts with label multi threading. Show all posts

Monday, May 12, 2014

iOS 7.1 App Life Cycle

Launching an app into the foreground





Launching an app into the background 


iOS regulates background processing very tightly, and offers three approaches to implement it:
  • Register a Background Task - If an application needs to complete an important task, it can ask iOS not to interrupt the task when the application moves into the background. For example, an application might need to finish logging in a user, or finish downloading a large file.
  • Register as a Background-Necessary Application - An app can register as a specific type of application that has known, specific backgrounding requirements, such as Audio, VoIP, External Accessory,Newsstand, and Location. These applications are allowed continuous background processing privileges as long as they are performing tasks that are within the parameters of the registered application type.
  • Enable Background Updates - Applications can trigger background updates with Region Monitoring or by listening for Significant Location Changes. As of iOS 7, applications can also register to update content in the background using Background Fetch or Remote Notifications.



Change of App State in iOS 






The App Launch Sequence on iOS

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 Filesgroup. Usually, you never have to look at that file but let’s do. This is the entire code of main():
1
2
3
4
5
6
7
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, anautorelease 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 theNSMainNibFile 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’sdelegate. 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 UIApplicationinstance 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-knownapplication: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.

Regards or Taken from : http://oleb.net/blog

Monday, April 28, 2014

Blocks and Multithreading in iOS

Blocks are important in iOS programming because they are used to implement multithreading with GCD (Grand Central Dispatch).  A block is a chunk of code contained in {}.  To indicate the beginning of a block use a caret (^). Here is a block that prints a string. 
^{
    NSString *type = "Demo";
    NSLog(@" %@", type);
};
We use the caret (^) character to define the beginning of a block literal, and if there are any arguments they are contained in () followed by the block code itself contained in {}. An example of a block that takes an int as an argument and returns the square value. 
^(int value){
    return value*value;
}
You don't have to declare the return type of a block, it can be inferred from the code in the block. Most of the time we pass the block to a method directly, but we can also assign it to a block variable. The syntax for declaring a block variable is "return_type (^name) (arguments)" If we declare a block variable "square" and assign to it the block we used in the previous example, it would look like this. 
int (^square) (int) = ^(int value){
    return value*value;
};
You can call this block just like a function. 
int square_value = square(5);
We can also create a type definition for a variable that holds a block by using typedef. The syntax is similar to declaring a block variable name "typedef return_type (^type_name) (arguments)" Then we can declare the block variables with "type_name block_name = ^(arguments){...}"

Blocks are closures, therefore they have access to local variables when the block is created. Local variables are read only. If you want to be able to change the value of local variables, they need to be declared with __block.

To implement multithreading in iOS we use GCD (Grand Central Dispatch). Any operation that takes a long time to execute might lock the UI (User Interface) while it is being performed. For example, anything network related, like getting an image from a remote server. If the image is large enough, it might take a minute or two to download. If we don't use a different thread for downloading the image, the whole app will be locked for the duration of the time it takes to download the image. In cases like this it is a good idea to use GCD to improve the user experience. This is where blocks become very useful to programmers.

GCD is a C API, therefore it is not object oriented API. The most basic use of GCD is to create a queue, and then to put blocks on that queue to be executed in a different thread by the system. The function used to create a queue and put a block on one are as follows 
//to create a queue
dispatch_queue_t dispatch_queue_create(const char *label, NULL);

//to put a block on a queue
void dispatch_async(dispatch_queue_t queue, dispatch_block_t block):
^dispatch_block_t is a prototype of blocks submitted that takes no arguments and doesn't return anything. Let's say we have a method that downloads an xml file from the internet. 
-(void)fetchXML
{
    NSString *URLString = @"example.com/example.xml";
    NSURL *URL = [NSURL URLWithString:[URLString
                        stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
    NSData *dataXML = [NSData dataWithContentsOfURL:URL];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:dataXML];
    [xmlParser setDelegate:self];
    BOOL success = [xmlParser parse];
    // test the result
    if (success) {
        NSLog(@"No errors");
    } else {
        NSLog(@"Error");
    }
}
To execute the fetching of the file on a different thread, we need to do the following modifications to our code. Create a queue and then put the code as a block on that queue. 
-(void)fetchXML
{
    dispatch_queue_t fetchQueue = dispatch_queue_create("fetch xml", NULL);
    dispatch_async(fetchQueue, ^{
        NSString *URLString = @"example.com/example.xml";
        NSURL *URL = [NSURL URLWithString:[URLString
                         stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
        NSData *dataXML = [NSData dataWithContentsOfURL:URL];
        NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:dataXML];
        [xmlParser setDelegate:self];
        BOOL success = [xmlParser parse];
        // test the result
        if (success) {
            NSLog(@"No errors");
        } else {
            NSLog(@"Error");
        }
   });
}
There is just one more rule about using GCD for multithreading. When we have code that makes changes to UIKit objects, we need to dispatch that block of code in the main queue. The way to get the main queue is with "dispatch_get_main_queue". 
dispatch_async(dispatch_get_main_queue(), ^{....});



Regards : http://code-and-coffee.blogspot.in/