Monday, March 21, 2011

iPhone/iPad Technical Interview Question(FAQ) with answers(Part 1)

Q1.What is the iPhone Application Entry point?
A. The main function:
int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;

Q2.What is the GUI Entry Point?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    // Override point for customization after application launch.

    // Add the view controller's view to the window and display.
    [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    return YES;

Q3.What is the Model structure of iPhone Application?
@interface RootViewController : UITableViewController {
 NSArray *tableDataSource;

NSString *CurrentTitle;
NSInteger CurrentLevel;
IBOutlet UITableView * newsTable
UIActivityIndicatorView * activityIndicator
CGSize cellSize
NSMutableArray * stories
NSMutableDictionary * item;
NSString * currentElement
NSMutableString * currentTitle, * currentDate, * currentSummary, * currentLink

@property (nonatomic, retain) NSArray *tableDataSource;
@property (nonatomic, retain) NSString *CurrentTitle;
@property (nonatomic, readwrite) NSInteger CurrentLevel;

Q4.What is the View structure of iPhone Application?
@interface loancalculatorViewController : UIViewController {
IBOutlet UITextField *tbxLoanAmount;
IBOutlet UITextField *annualInterestRate;
IBOutlet UITextField *noOfYears;
IBOutlet UILabel *monthlyPayment;
IBOutlet UILabel *totalInterest;
IBOutlet UILabel *totalPayment;

@property (nonatomic,retain) UITextField *tbxLoanAmount;
@property (nonatomic,retain) UITextField *annualInterestRate;
@property (nonatomic,retain) UITextField *noOfYears;
@property (nonatomic,retain) UILabel *monthlyPayment;
@property (nonatomic,retain) UILabel *totalInterest;
@property (nonatomic,retain) UILabel *totalPayment;

Q5.What is the Controller structure of iPhone Application?

@interface RootViewController : UITableViewController {
mainView* myMainView;
- (id)init;
- (void)dealloc;
- (void)loadView;

Q6. What are Delegates in Objective-C?

A delegate allows one object to send messages to another object when an event happens.
A delegate is a pointer to an object with a set of methods the delegate-holder knows how to call. In other words, it's a mechanism to enable specific callbacks from a later-created object.

For example: when we create an object of UITableView like: UITableView *myTable;
then some methods like:


automatically called. These methods are called delegated.

Q7. What is the need of these Delegates?
 To execute some of must to do actions, we need these delegates.
For example: for a table it is must decided that, 
  • How many row will be there.
  • What will be the content on cell of each row.
  • What will happen after selecting the row.

Q8. How Memory Management is handle in iphone?

Q9. What is MVC ?
MVC (Model View Controller) is a design pattern used in services architectures. MVC separate the software architecture into three distinct elements. The 'Model' is how the underlying data is structured. The 'View' is what is presented to the user or consumer. The 'Controller' is the element that performs the processing. More.....

Q10.  MVC supports loose or tight coupling?
MVC supports both loose and tight coupling, because there is usually a tight coupling
between the view and the controller because user actions are difficult to interpret without details of the presentation. For example:
   • What object mouse clicked on 
   • What text area user typed into
Actions must be interpreted in terms of presentation
View has the information to map points in view to application objects

Refer the figure in this post.
•    View needs to know about model. Controller needs to know about model and view, So view and the controller are tightly coupled.
•    Model doesn’t need to know about either’s design, So Model loosely coupled to view/controller

All The Best :)

Next(Part 2)….

MVC Architecture of iPhone App

The main aim of the MVC architecture  is to separate the business logic and application data from the presentation data to the user.
Here are the reasons why we should use the MVC design pattern.
  1. They are resuable : When the problems occurs, there is no need to invent a new solution, we just have to follow the pattern and adopt it as necessary.
  2. They are expressive: By using the MVC design pattern our application becomes more expressive.
1).  Model: The model object knows about all the data that need to be displayed. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application. The model represents enterprise data and the business rules that govern access to and updates of this data. Model is not aware about the presentation data and how that data will be displayed to the browser.
2). View : The view represents the presentation of the application. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it. The view is not dependent on the application logic. It remains same if there is any modification in the business logic. In other words, we can say that it is the responsibility of the of the view's to maintain the consistency in its presentation when the model changes.
3). Controller:  Whenever the user sends a request for something then it always go through the controller. The controller is responsible for intercepting the requests from view and passes it to the model for the appropriate action. After the action has been taken on the data, the controller is responsible for directing the appropriate view to the user. In  GUIs, the views and the controllers often work very closely together.

MVC in iPhone:
The Model-View-Controller (MVC) design pattern is a way of dividing your code into independent functional areas. The model portion defines your application’s underlying data engine and is responsible for maintaining the integrity of that data. The view portion defines the user interface for your application and has no explicit knowledge of the origin of data displayed in that interface. The controller portion acts as a bridge between the model and view and facilitates updates between them.

The Model, View, Controller (MVC) design pattern is one way of looking at software development that the Apple engineers put into the Cocoa frameworks (part of the iPhone system). Here are the three pieces of the MVC pattern:
- Model: the abstract data about your problem space
- View: the visual elements of the application
- Controller: code that glues the model and view together

As an example, think of an iPhone app that is used to maintain a task list. The app would simply display a list of tasks that users check off as they are completed. Here is how the MVC pattern would fit into this app.
Our example app model would be an object that contains the list of tasks, the state of each task and some code to make the task data persistent.

Our view would be an object that contained a table with cells that allowed text entry and user interaction (GUI elements).

Our app’s controller object would know about the Model and the View. Controller will respond to user input and inform the view to update it’s visual elements or have the Model perform some action to the underlying data.


iPhone/iPad design patterns

Design Patterns
design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved. Many patterns imply object-orientation or more generally mutable state, and so may not be as applicable in functional programming languages, in which data is immutable or treated as such.

The Model-View-Controller (MVC) design pattern is a way of dividing your code into independent functional areas. The model portion defines your application’s underlying data engine and is responsible for maintaining the integrity of that data. The view portion defines the user interface for your application and has no explicit knowledge of the origin of data displayed in that interface. The controller portion acts as a bridge between the model and view and facilitates updates between them.
The delegation design pattern is a way of modifying complex objects without subclassing them. Instead of subclassing, you use the complex object as is and put any custom code for modifying the behavior of that object inside a separate object, which is referred to as the delegate object. At pre-defined times, the complex object then calls the methods of the delegate object to give it a chance to run its custom code.
Controls use the target-action design pattern to notify your application of user interactions. When the user interacts with a control in a predefined way (such as by tapping a button), the control sends a message (the action) to an object you specify (the target). Upon receiving the action message, the target object can then respond in an appropriate manner (such as by updating application state in response to the button push).
Managed memory model
The Objective-C language uses a reference-counted scheme for determining when to release objects from memory. When an object is first created, it is given a reference count of 1. Other objects can then use the retain, release, or autorelease methods of the object to increase and decrease that reference count appropriately. When an object’s reference count reaches 0, the Objective-C runtime calls the object’s cleanup routines and then deallocates it.

KVC (Key Value Coding)
The KVC is a concept to directly getting and setting specific properties of an object.
In  key value coding we have to pass a "Key" (any string) for getting and setting the property associated with that key.
Its not necessary to use KVC, we can also complete our project without using it. 
However, it is one of the best code patterns for reducing repetitious code and making classes more
reusable by decoupling actions from properties and data.


Tuesday, March 15, 2011

Gif animation in iPhone

Gif animation in iPhone/iPad app OR How to implement .gif file in iPhone/iPad app.

Here we will see how an UIImage can be used to implement similar effect as in .gif animation like this:

To show an animation or to implement .gif file in your iPhone/iPad app view follow these steps:

Step 1: Create new project in xcode and name it as "gif_Animation".

Step 2: First of all split the .gif file into frames (because gif file is nothing but a series of images, and also iPhone/iPad app does not directly support gif file).
Here for example we split the .gif  file and save frame as:

  • frame1.jpg
  • frame2.jpg
  • frame3.jpg
  • frame4.jpg
  • frame5.jpg

Step 3: Add all frames into resource folder.

Step 4: Now open "gif_AnimationViewController.h" and add this code:

#import <UIKit/UIKit.h>
@interface gif_AnimationViewController : UIViewController {

 UIImageView   *animatedImages;
 NSMutableArray *imageArray;
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
Step 5: Now open "gif_AnimationViewController.m" and add this code: 

#import "gif_AnimationViewController.h"

#define IMAGE_COUNT       5
#define IMAGE_HEIGHT      480 
#define IMAGE_WIDTH       320

@implementation gif_AnimationViewController

imageArray = [[NSMutableArray alloc] initWithCapacity:IMAGE_COUNT];
// Array to hold jpg images

imageArray = [NSMutableArray arrayWithObjects: [UIImage imageNamed:@"frame1.jpg"], [UIImage imageNamed:@"frame2.jpg"], [UIImage imageNamed:@"frame3.jpg"], [UIImage imageNamed:@"frame4.jpg"], [UIImage imageNamed:@"frame5.jpg"], nil];
// Animated images - centered on screen
animatedImages = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,IMAGE_WIDTH, IMAGE_HEIGHT)];
animatedImages.animationImages = [NSArray arrayWithArray:imageArray];
// One cycle through all the images takes 1.5 seconds
animatedImages.animationDuration =1;
// Repeat forever
animatedImages.animationRepeatCount = -1;
// Add subview and make window visible
[self.view addSubview:animatedImages];
// Start it up
[animatedImages startAnimating];
// Wait 5 seconds, then stop animation
[self performSelector:@selector(stopAnimation) withObject:nil afterDelay:8.0];
- (void)stopAnimation
[animatedImages stopAnimating];

//if we want to stop animation by user touch without any delay then use this
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
[self performSelector:@selector(stopAnimation) withObject:nil afterDelay:0.0];

// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    return self;

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.

- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;

- (void)dealloc {
    [super dealloc];
[imageArray release];
[animatedImages release];


Step 6: Now run your project, it will look like this:

 Happy Coding :)