Getting Integer Month, Day and Year from NSDate | Explain the use of NSDateComponents? | iOS Interview Question | iOS Programmer Guide

We can get day, month and year components of NSDate in integer form. For example, if the date is 1/2/2014 then we should get 1, 2 and 2014 separately as an integer.

We can achieve this with the help of the NSDateComponents. NSDateComponents helps you to get day, month and year in integer format from NSDate. The objective-c code snippet for this is given below:

NSDate *currentDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate]; // Get necessary date components

 [components month]; //gives you month
 [components day]; //gives you day
 [components year]; // gives you year

for more details on NSDateComponents

How to get UTC Date and Time Using Objective-C? | iOS Interview Question | iOS Programmer Guide

We can get UTC date & time with the help of the below objective c user defined function.

-(NSString *)getUTCFormateDate:(NSDate *)localDate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [dateFormatter setTimeZone:timeZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:localDate];
    [dateFormatter release];
    return dateString;

Explain Relationship of the Frame, Bounds, and Center Properties in UIView | iOS Interview Question | iOS Programmer Guide

A view object tracks its size and location using its framebounds, and center properties:
  • The frame property contains the frame rectangle, which specifies the size and location of the view in its superview’s coordinate system.
  • The bounds property contains the bounds rectangle, which specifies the size of the view (and its content origin) in the view’s own local coordinate system.
  • The center property contains the known center point of the view in the superview’s coordinate system.

Explain UIView Drawing Cycle in iOS App? | iOS Interview Question | iOS Programmer Guide

The UIView class uses an on-demand drawing model for presenting content. When a view first appears on the screen, the system asks it to draw its content. The system captures a snapshot of this content and uses that snapshot as the view’s visual representation. If you never change the view’s content, the view’s drawing code may never be called again. The snapshot image is reused for most operations involving the view. If you do change the content, you notify the system that the view has changed. The view then repeats the process of drawing the view and capturing a snapshot of the new results.
When the contents of your view change, you do not redraw those changes directly. Instead, you invalidate the view using either the setNeedsDisplay or setNeedsDisplayInRect: method. These methods tell the system that the contents of the view changed and need to be redrawn at the next opportunity. The system waits until the end of the current run loop before initiating any drawing operations. This delay gives you a chance to invalidate multiple views, add or remove views from your hierarchy, hide views, resize views, and reposition views all at once. All of the changes you make are then reflected at the same time.

Explain About iOS Notification? | iOS Interview Question | iOS Programmer Guide

A notification is a message sent to one or more observing objects to inform them of an event in a program. The notification mechanism of Cocoa follows a broadcast model. It is a way for an object that initiates or handles a program event to communicate with any number of objects that want to know about that event. These recipients of the notification, known as observers, can adjust their own appearance, behavior, and state in response to the event. The object sending (or posting) the notification doesn’t have to know what those observers are. Notification is thus a powerful mechanism for attaining coordination and cohesion in a program. It reduces the need for strong dependencies between objects in a program (such dependencies would reduce the reusability of those objects). Many classes of the Foundation, AppKit, and other Objective-C frameworks define notifications that your program can register to observe.
The centerpiece of the notification mechanism is a per-process singleton object known as the notification center (NSNotificationCenter). When an object posts a notification, it goes to the notification center, which acts as a kind of clearing house and broadcast center for notifications. Objects that need to know about an event elsewhere in the application register with the notification center to let it know they want to be notified when that event happens. Although the notification center delivers a notification to its observers synchronously, you can post notifications asynchronously using a notification queue (NSNotificationQueue).
Broadcasting a notification

The Notification Object

A notification is represented by an instance of the NSNotification class. A notification object contains several bits of state: a unique name, the posting object, and (optionally) a dictionary of supplementary information, called the userInfo dictionary. When a notification is delivered to an interested observer, the notification object is passed in as an argument of the method handling the notification.

Observing a Notification

To observe a notification, obtain the singleton NSNotificationCenter instance and send it anaddObserver:selector:name:object: message. Typically, this registration step is done shortly after your application launches. The second parameter of the addObserver:selector:name:object: method is a selector that identifies the method that you implement to handle the notification. The method must have the following signature:
- (void)myNotificationHandler:(NSNotification *)notif;
In this handling method, you can extract information from the notification to help you in your response, especially data in the userInfo dictionary (if one exists).

Posting a Notification

Before posting a notification, you should define a unique global string constant as the name of your notification. A convention is to use a two- or three-letter application-specific prefix for the name, for example:
NSString *AMMyNotification = @"AMMyNotication";
To post the notification, send a postNotificationName:object:userInfo: (or similar) message to the singleton NSNotificationCenter object. This method creates the notification object before it sends the notification to the notification center.

Identifying iOS Application’s Documents Directory | iOS Interview Question | iOS Programmer Guide

We can easily identify the documents directory of an iOS Application with the help of 'NSSearchPathForDirectoriesInDomains' as given in the following objective-C code snippet

// Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(
      NSDocumentDirectory, NSUserDomainMask, YES);

Purpose of PCH file in Xcode? | iOS Interview Question | iOS Programmer Guide


.pch file is a prefix header file which is automatically created by xcode.

It is compiled and stored in cache, and automatically included in every source file during the compilation time. 

Note: Precompiling the prefix header will be most effective if the contents of the prefix header or any file it includes change rarely. If the contents of the prefix header or any file it includes change frequently, there may be a negative impact to overall build time.

String Split Equivalent in iOS xcode | iOS Interview Question | iOS Programmer Guide

The C# equivalent of String split in iOS is possible. The easiest way to split a NSString into an NSArray is the following:
NSString *string = @"hello,world";
NSArray *stringArray = [string componentsSeparatedByString: @","];

Explain the Purpose of main Function in Xcode Project? | iOS Interview Question | iOS Programmer Guide

Like any C-based app, the main entry point for an iOS app at launch time is the main function. In an iOS app, the main function is used only minimally. Its main job is to hand control to the UIKit framework. Therefore, any new project you create in Xcode comes with a default main function like the one shown in Listing 3-1. With few exceptions, you should never change the implementation of this function.
Listing 3-1  The main function of an iOS app
#import <UIKit/UIKit.h>
int main(int argc, char *argv[])
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([MyAppDelegate class]));

Determining iOS Apps Default Settings If Changed | iOS Programmer Guide

If you have created a custom settings using the standard root.plist for the iphone App. There is a way to determine when the user changes those settings by listening to NSUSerDefaultsDidChange-notifications.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultsChanged) name:NSUserDefaultsDidChangeNotification object:nil];

Whenever the NSUserDefaults changes, defaultsChanged will be called. However, don't forget to call [[NSNotificationCenter defaultCenter] removeObserver:self]; when you want to stop listening for these notifications.

And there is no real way to determine which settings were changed, but if you look for something specific, try storing the old version when the notifications gets run, then check against that setting next time.

Explain Various iOS App State Changes? | iOS Interview Question | iOS Programmer Guide

Not runningThe app has not been launched or was running but was terminated by the system.
InactiveThe app is running in the foreground but is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state.
ActiveThe app is running in the foreground and is receiving events. This is the normal mode for foreground apps.
BackgroundThe app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state. For information about how to execute code while in the background
SuspendedThe app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code.
When a low-memory condition occurs, the system may purge suspended apps without notice to make more space for the foreground app.
Figure 1  State changes in an iOS app

Explain iOS App Launch Cycle? | iOS Interview Question | iOS Programmer Guide

When your app is launched, it moves from the not running state to the active or background state, transitioning briefly through the inactive state. As part of the launch cycle, the system creates a process and main thread for your app and calls your app’s main function on that main thread. The default main function that comes with your Xcode project promptly hands control over to the UIKit framework, which does most of the work in initializing your app and preparing it to run.
Below figure shows the sequence of events that occurs when an app is launched into the foreground, including the app delegate methods that are called.
Figure 1  Launching an app into the foreground
Application life cycle
If your app is launched into the background instead—usually to handle some type of background event—the launch cycle changes slightly to the one shown in Figure 3-3. The main difference is that instead of your app being made active, it enters the background state to handle the event and then is suspended shortly afterward. When launching into the background, the system still loads your app’s user interface files but it does not display the app’s window.
Figure 2  Launching an app into the background
To determine whether your app is launching into the foreground or background, check the applicationState property of the shared UIApplication object in yourapplication:willFinishLaunchingWithOptions: or application:didFinishLaunchingWithOptions: delegate method. When the app is launched into the foreground, this property contains the value UIApplicationStateInactive. When the app is launched into the background, the property contains the valueUIApplicationStateBackground instead. You can use this difference to adjust the launch-time behavior of your delegate methods accordingly.

What are the Types of Segues In Xcode? | iOS Interview Question | iOS Programmer Guide

  • Push. A push segue adds the destination view controller to the navigation stack. Push segues may only be used when the source view controller is connected to a navigation controller.
  • Modal. A modal segue is simply one view controller presenting another controller modally, requiring a user to perform some operation on the presented controller before returning to the main flow of the app. A modal view controller isn’t added to a navigation stack; instead, it’s generally considered to be a child of the presenting view controller. The presenting view controller is responsible for dismissing the modal view controller it created and presented.
  • Custom. You can define your own custom transition by subclassing UIStoryboardSegue.
  • Unwind. An unwind segue moves backward through one or more segues to return the user to an existing instance of a view controller. You use unwind segues to implement reverse navigation.

Explain Navigation Controllers In Xcode? | iOS Interview Question | iOS Programmer Guide

If your app has more than one content view hierarchy, you need to be able to transition between them. For this, you’ll use a specialized type of view controller: a navigation controller (UINavigationController). Anavigation controller manages transitions backward and forward through a series of view controllers, such as when a user navigates through email accounts, inbox messages, and individual emails in the iOS Mail app.
The set of view controllers managed by a particular navigation controller is called its navigation stack. Thenavigation stack is a last-in, first-out collection of custom view controller objects. The first item added to the stack becomes the root view controller and is never popped off the stack. Other view controllers can be pushed on or popped off the navigation stack.
Although a navigation controller’s primary job is to manage the presentation of your content view controllers, it’s also responsible for presenting custom views of its own. Specifically, it presents a navigation bar—the view at the top of the screen that provides context about the user’s place in the navigation hierarchy—which contains a back button and other buttons you can customize. Every view controller that’s added to the navigation stack presents this navigation bar. You are responsible for configuring the navigation bar.
You generally don’t have to do any work to pop a view controller off of the navigation stack; the back button provided by the navigation controller handles this for you. However, you do have to manually push a view controller onto the stack. You can do this using storyboards

Explain Controls In Xcode? | iOS Interview Question | iOS Programmer Guide

control is a user interface object such as a button, slider, or switch that users manipulate to interact with content, provide input, navigate within an app, and perform other actions that you define. Controls provide a way for your code to receive messages from the user interface.
When a user interacts with a control, a control event is created. A control event represents various physical gestures that users can make on controls, such as lifting a finger from a control, dragging a finger onto a control, and touching down within a text field.
There are three general categories of event types:
  • Touch and drag events. Touch and drag events occur when a user interacts with a control with a touch or drag. There are several available touch event stages. When a user initially touches a finger on a button, for example, the Touch Down Inside event is triggered; if the user drags out of the button, the respective drag events are triggered. Touch Up Inside is sent when the user lifts a finger off the button while still within the bounds of the button’s edges. If the user has dragged a finger outside the button before lifting the finger, effectively canceling the touch, the Touch Up Outside event is triggered.
  • Editing events. Editing events occur when a user edits a text field.
  • Value-changed events. Value-changed events occur when a user manipulates a control, causing it to emit a series of different values.
As you define the interactions, know the action that’s associated with every control in your app and then make that control’s purpose obvious to users in your interface.

Explain Outlets In Xcode? | iOS Interview Question | iOS Programmer Guide

Outlets provide a way to reference objects from your interface—the objects you added to your storyboard—from source code files. You create an outlet by Control-dragging from a particular object in your storyboard to a view controller file. This creates a property for the object in your view controller file, which lets you access and manipulate that object from code at runtime. For example, in the second tutorial, you’ll create an outlet for the text field in your ToDoList app to be able to access the text field’s contents in code.
Outlets are defined as IBOutlet properties.
  1. @property (weak, nonatomic) IBOutlet UITextField *textField;
The IBOutlet keyword tells Xcode that you can connect to this property from Interface Builder.

Explain Actions In Xcode? | iOS Interview Question | iOS Programmer Guide

An action is a piece of code that’s linked to some kind of event that can occur in your app. When that event takes place, the code gets executed. You can define an action to accomplish anything from manipulating a piece of data to updating the user interface. You use actions to drive the flow of your app in response to user or system events.
You define an action by creating and implementing a method with an IBAction return type and a senderparameter.
  1. - (IBAction)restoreDefaults:(id)sender;
The sender parameter points to the object that was responsible for triggering the action. The IBActionreturn type is a special keyword; it’s like the void keyword, but it indicates that the method is an action that you can connect to from your storyboard in Interface Builder (which is why the keyword has the IB prefix). 

Purpose of View Controllers in Xcode | iOS Interview Question | iOS Programmer Guide

After you’ve built a basic view hierarchy, your next step is to control the visual elements and respond to user input. In an iOS app, you use a view controller (UIViewController) to manage a content view with its hierarchy of subviews.

image: ../Art/view_layer_objects_2x.png

A view controller isn’t part of the view hierarchy and it’s not an element in your interface. Instead, it manages the view objects in the hierarchy and provides them with behavior. Each content view hierarchy that you build in your storyboard needs a corresponding view controller, responsible for managing the interface elements and performing tasks in response to user interaction. This usually means writing a customUIViewController subclass for each content view hierarchy. If your app has multiple content views, you use a different custom view controller class for each content view.
View controllers play many roles. They coordinate the flow of information between the app’s data model and the views that display that data, manage the life cycle of their content views, and handle orientation changes when the device is rotated. But perhaps their most obvious role is to respond to user input.
You also use view controllers to implement transitions from one type of content to another. Because iOS apps have a limited amount of space in which to display content, view controllers provide the infrastructure needed to remove the views of one view controller and replace them with the views of another.
To define interaction in your app, make your view controller files communicate with the views in your storyboard. You do this by defining connections between the storyboard and source code files through actions and outlets.

Functionality of @autoreleasepool | iOS Interview Question | iOS Programmer Guide

The @autoreleasepool statement is there to support memory management for your app. Automatic Reference Counting (ARC) makes memory management straightforward by getting the compiler to do the work of keeping track of who owns an object; @autoreleasepool is part of the memory management infrastructure.

Responsibility of UIApplicationMain in iOS XCode? | iOS Interview Question | iOS Programming Guide

UIApplicationMain function, will be automatically called in main.m source file. The UIApplicationMain function creates an application object that sets up the infrastructure for your iOS app to work with the iOS system. This includes creating a run loop that delivers input events to your app.

  1. @autoreleasepool {
  2. return UIApplicationMain(argc, argv, nil, NSStringFromClass([XYZAppDelegate class]));
  3. }
The call to UIApplicationMain creates two important initial components of your app:
  • An instance of the UIApplication class, called the application object. The application object manages the app event loop and coordinates other high-level app behaviors. This class, defined in the UIKit framework, doesn’t require you to write any additional code to get it to do its job.

  • An instance of the XYZAppDelegate class, called the app delegate. Xcode created this class for you as part of setting up the Empty Application template. The app delegate creates the window where your app’s content is drawn and provides a place to respond to state transitions within the app. This window is where you write your custom app-level code. Like all classes, the XYZAppDelegate class is defined in two source code files in your app: in the interface file, XYZAppDelegate.h, and in the implementation file, XYZAppDelegate.m.