Παρασκευή, 30 Μαρτίου 2012

Application life cycle - UIApplication-Active-Inactive-EnterBackground - 5sec rule

After one month of study, a review is good. Lets see from Documentation the life cycle.
short notes:

  • The design of the UIKit framework incorporates many of the same design patterns found in Cocoa applications in Mac OS X. (MVC, Block objects, Delegation, Target-action, Managed memory model, threads and concurrent programming).
  • The UIApplication object manages the application event loop and coordinates other high-level behaviors for your application.
  • The application delegate is a custom object that you provide at application launch time, usually by embedding it in your application’s main nib file.The UIApplication object also notifies this object when specific application-level events occur
  • View controller objects manage the presentation of your application’s content. Typically, this involves creating the views to present that content and managing the interactions between the views and your application’s data model objects.
  • The main Function. In an iOS application, the main function is used only minimally. Its main job is to hand control to the UIKit framework. 
  • The UIApplicationMain function at the heart of your application’s main function takes four parameters and uses them to initialize the application.The third parameter identifies the name of the application’s principal class. This is the class responsible for running the application.Monitoring the high-level behavior of your application is the responsibility of the application delegate object, which is a custom object that you provide. 
  • Application states: Not running, Inactive, Active, Background, Suspended
  • At launch time, an application moves from the not-running state to the active or background state. During the initial startup sequence, the application calls its delegate’s application:didFinishLaunchingWithOptions: method, followed by either the applicationDidBecomeActive: or applicationDidEnterBackground: method (depending on whether it is transitioning to the foreground or background).
  • Check the contents of the launch options dictionary for information about why the application was launched, and respond appropriately.
  • You should strive to make your application:didFinishLaunchingWithOptions: method as lightweight as possible. Although there are any number of custom initialization tasks you could perform in this method, it has only around 5 seconds to do its initialization and return. If it takes too long to complete its tasks, the system might kill the application for being unresponsive. Ways to make this method lightweight include initiating tasks asynchronously or moving any long-running tasks to secondary threads. Making the method lightweight is especially important for network-based tasks that could take an indeterminate amount of time to complete.
  • When your application:didFinishLaunchingWithOptions: method is called, the applicationState property of the UIApplication object is already set to the appropriate state for your application (UIApplicationStateInactiveUIApplicationStateBackground). you can use this information to prepare your application appropriately.
  • "Being a Responsible, Multitasking-Aware Application."
  • Your delegate’s applicationDidEnterBackground: method has approximately 5 seconds to finish any tasks and return. If the method does not return before time runs out, your application is killed and purged from memory. If you still need more time to perform tasks, call the beginBackgroundTaskWithExpirationHandler: method to request background execution time and then start any long-running tasks in a secondary thread.
  • The UIApplicationDidEnterBackgroundNotification notification is also sent to let interested parts of your application know that it is entering the background.
  • To that end, there are at least two things you should always do in your applicationDidEnterBackground: method: Prepare your application to have its picture taken Save user data and application state information
  • ....Responding to Interruptions to be continue 








last update 30/3/2012

What’s this resignFirstResponder business?

Follows section from The Big Nerd Ranch Guide - Objective C: 

Some view objects are also controls - views that the user can interact with. 
Buttons, sliders and text fields are examples of controls. 

When there are controls on the screen, one of them can be the first responder

Having first responder status means that the control gets dibs on handling any text input from the keyboard or any shake events (such as “Shake to Undo”).

When the user taps a control that can accept first responder status, that control is sent the becomeFirstResponder message. Until another control becomes the first responder or the current control is sent the resignFirstResponder message, that control will keep this status and receive keyboard and shake input. 

When a text input control (like a text field) becomes the first responder, the keyboard materializes on the screen. As long as the current first responder is a control that accepts text input, the keyboard will remain on the screen. 

At the end of addTask:, we tell the text field to resign its status , which causes the keyboard to dematerialize. 

[taskField[resignFirstResponder];


image from documentation

Documentation:
A view that is first responder accepts key events and action messages before other objects in a window. It also typically takes part in the key loop (see“Keyboard Interface Control”). By default, view objects refuse first-responder status by returning NO in acceptsFirstResponder. If you want your custom view to respond to key events and actions, your class must override this method to return YES:
- (BOOL) acceptsFirstResponder{
return YES;
}

manually-tricky way to send retain in ARC

You cannot actually send retain, release messages manually
 [self performSelector:NSSelectorFromString(@"retain")])



Τετάρτη, 28 Μαρτίου 2012

A nice simple example of MVC (Model View Controller) pattern

In the following code from examples of The Big Nerd Ranch Guide (objective C) you can see a nice example of Model -View - Controller pattern in action.


  • We build each view separately. We use the frame to ensure the placing position on the screen. 
  • We connect our instance variables with the views. 
  • We connect the action-target mechanism of UIButton with the BNRAppDelegate as target (via the self pointer that targets on BNRAppDelegate). We also say that the ACTION will be the method addTask (with the action:@selector(addTask:))





#pragma mark

Objective-C programmers often use this construct to group their methods within a class.
Xcode knows about it, too.

Look how the #pragma mark works in the following captured image.


#source: example from The Big Nerd Ranch Guide - Objective C
-------------------------------------------------------------------------------------------------------
More information from [iOS developer:tips];

Xcode and #pragma mark
Posted on September 30, 2008 by John Muchow in Xcode


I’ve started using #pragma mark directives in my code to help with organization as my implementation files grow. #pragma mark is simple to use, for example, insert the following to call out initialization code:
1
2
#pragma mark -
#pragma mark Initialization
Once this is in place, the Functions Menu (in the navigation bar) which shows a list of locations within a source file (e.g. definitions of classes, functions and methods) will display a new marker with the label "Initialization." The code in line 1 will add a line separator inside the Functions Menu, in this example, with the line appearing above the "Initialization" marker.
The figure that follows shows an example of how you might use #pragma mark to divide up various sections of your code.


More recently discuss at linkedin

Delegate - Delegation - Why the first class in iOS projects ends in AppDelegate?

#source: The Big Nerd Ranch Guide - Objective C
___________________________________________
Lets say we create a new iOS project with name XXF. 

It creates automatically the XXFAppDelegate. During the phase of the first launch, an instance of UIApplication is created to control your applications state and act as liaison to the operating system.

 An instance of XXFAppDelegate is also created and set the delegate of the UIApplication instance (which explains the name "app delegate"").



From Documentation
___________________________________________

Delegation is a mechanism used to avoid subclassing complex UIKit objects, such as the UIApplication object. Instead of subclassing and overriding methods in a complex object, you use that object unmodified and put your custom code inside a delegate object. As interesting events occur, the complex object sends messages to your delegate object. You can use these hooks to execute your custom code and implement the behavior you need.
Important: The delegate design pattern is intended to save you time and effort when creating applications and is therefore a very important pattern to understand. For an overview of the key design patterns used by iOS applications, see “Fundamental Design Patterns.” For a more detailed description of delegation and other UIKit design patterns, see Cocoa Fundamentals Guide






 From dictionary: 
Delegate n. : a person sent or authorized to represent others, in particular an elected representative sent to a conference.


Τρίτη, 27 Μαρτίου 2012

NSSearchPathForDirectoriesInDomains


//Helper function to fetch the path to our to-do data stored on disk 
NSString *docPath()
{
    NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                            NSUserDomainMask,   
                                                            YES);
    return [[pathList objectAtIndex:0] stringByAppendingPathComponent:@"data.td"];
            
}

#:source: example from the Big Nerd Ranch Guide - Objective - C - Programming

and follows the documentation :) 

NSSearchPathForDirectoriesInDomains

Creates a list of directory search paths.
NSArray * NSSearchPathForDirectoriesInDomains (
   NSSearchPathDirectory directory,
   NSSearchPathDomainMask domainMask,
   BOOL expandTilde
);
Discussion
Creates a list of path strings for the specified directories in the specified domains. The list is in the order in which you should search the directories. IfexpandTilde is YES, tildes are expanded as described in stringByExpandingTildeInPath.
You should consider using the NSFileManager methods URLsForDirectory:inDomains: andURLForDirectory:inDomain:appropriateForURL:create:error:. which return URLs, which are the preferred format.
For more information on file system utilities, see “Creating Paths and Locating Directories

Property lists - XML - when to use - short notes



strong points: 

  • For situations where you need to store small amounts of persistent data—say less than a few hundred kilobytes—property lists offer a uniform and convenient means of organizing, storing, and accessing the data.
  • A property list can be stored in one of three different ways: in an XML representation, in a binary format, or in an “old-styleASCII format inherited from OpenStep.
  • In general, if your property list is relatively small, the benefits of XML property lists outweigh the I/O speed and compactness that comes with binary property lists. If you have a large data set, binary property lists, keyed archives, or custom data formats are a better solution
  • And although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.
  • If you are looking for a way to implement user or application preferences, Cocoa provides a class specifically for this purpose.See Preferences and Settings Programming Guide and Preferences Programming Topics for Core Foundation for more information.




A property list is a structured data representation used by Cocoa and Core Foundation as a convenient way to store, organize, and access standard types of data. It is colloquially referred to as a “plist.”
Applications on iOS use property lists in their Settings bundle to define the list of options displayed to users.

Note: Although user and application preferences use property lists to structure and store data, you should not use the property list API of either Cocoa or Core Foundation to read and modify them. Instead, use the programming interfaces provided specifically for this purpose—see Preferences and Settings Programming Guide and Preferences Programming Topics for Core Foundation for more information.


A root property-list object is at the top of this hierarchy, and in almost all cases is a dictionary or an array. Note, however, that a root property-list object does not have to be a dictionary or array; for example, you could have a single string, number, or date, and that primitive value by itself can constitute a property list.

Property lists are based on an abstraction for expressing simple hierarchies of data. The items of data in a property list are of a limited number of types. Some types are for primitive values and others are for containers of values. The primitive types are strings, numbers, binary data, dates, and Boolean values. The containers are arrays—indexed collections of values—and dictionaries—collections of values each identified by a key. The containers can contain other containers as well as the primitive types. Thus you might have an array of dictionaries, and each dictionary might contain other arrays and dictionaries, as well as the primitive types. A root property-list object is at the top of this hierarchy, and in almost all cases is a dictionary or an array.

The static representation of a property list, which is used for storage, can be either XML or binary data. (The binary version is a more compact form of the XML property list.)

Abstract type
XML element
Cocoa class
Core Foundation type
array
<array>
CFArray (CFArrayRef)
dictionary
<dict>
CFDictionary (CFDictionaryRef)
string
<string>
CFString (CFStringRef)
data
<data>
CFData (CFDataRef)
date
<date>
CFDate (CFDateRef)
number - integer
<integer>
CFNumber (CFNumberRef, integer value)
number - floating point
<real>
CFNumber (CFNumberRef, floating-point value)
Boolean
<true/> or <false/>
NSNumber (boolValue == YES or boolValue == NO)

By convention, each Cocoa and Core Foundation object listed in above table is called a property-list object

example of exctracted xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
                  <dict>
                                    <key>shares</key>
                                    <integer>200</integer>
                                    <key>symbol</key>
                                    <string>AAPL</string>
                  </dict>
                  <dict>
                                    <key>shares</key>
                                    <integer>160</integer>
                                    <key>symbol</key>
                                    <string>GOOG</string>
                  </dict>
</array>
</plist>

And although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.

In most cases, however, methods provided by the NSPropertyListSerialization class should provide enough flexibility

For situations where you need to store small amounts of persistent data—say less than a few hundred kilobytes—property lists offer a uniform and convenient means of organizing, storing, and accessing the data.

In some situations, the property-list architecture may prove insufficient. If you need a way to store large, complex graphs of objects, objects not supported by the property-list architecture, or objects whose mutability settings must be retained, use archiving. See Archives and Serializations Programming Guide for more information

If you are looking for a way to implement user or application preferences, Cocoa provides a class specifically for this purpose. While the user defaults system does use property lists to store information, you do not have to access these plists directly. See Preferences and Settings Programming Guide and Preferences Programming Topics for Core Foundation for more information.

Note that property lists should be used for data that consists primarily of strings and numbers. They are very inefficient when used with large blocks of binary data.

A property list can be stored in one of three different ways: in an XML representation, in a binary format, or in an “old-style” ASCII format inherited from OpenStep. You can serialize property lists in the XML and binary formats. The serialization API with the old-style format is read-only.

XML property lists are more portable than the binary alternative and can be manually edited, but binary property lists are much more compact; as a result, they require less memory and can be read and written much faster than XML property lists. In general, if your property list is relatively small, the benefits of XML property lists outweigh the I/O speed and compactness that comes with binary property lists. If you have a large data set, binary property lists, keyed archives, or custom data formats are a better solution.

Δευτέρα, 26 Μαρτίου 2012

Callbacks - short notes


For Objective-C programmers, there are three-forms that a callback can take.
  • -       TARGET-ACTION: before the wait begins you say “When x happens, send this particular message to that particular object,” The object receiving the message is the target. The selector for the message is the action.
  • -       Helper objects: Before the wait begins, you say “Here is a helper object that conforms to your protocol. Send it messages when things happen”. Helper objects are often known as delegates or data sources.
  • -       Notifications: There is an object called the notification center. Before the wait begins, you say to the notification center “This object is waiting for these sorts of notifications. When one of those notifications arrives, send the object this message”. When x happens, an object posts a notification to the notification center, and the center forwards it on to your object.

Types of Callbacks
Target-Action
sending ONE    callback   to ONE object
timers,simple user interface controls(buttons, sliders etc)
Helper objects
(delegate or data source)
sending MANY callbacks to ONE object
NSURLConnection.
The most common type of helper object is the delegate
Notifications
sending MANY callbacks to Multiple object
Notification center


Notes:
-       Notification centers do not own their observers (they typically remove itself from notification in its dealloc method)
-       Objects do not own their delegates or data sources (if you create an object that is delegate or data source, your object need to “clear” himself in its dealloc method). Exception: NSURLConnection owns its delegate
-       Objects do not own their targets. (if you create an object that is a target, your object should zero the target pointer in its dealloc method).Exception: NSTimer owns it’s target.



#:From The Big Nerd Ranch Guide Objective C programming