Checking if a Method or Property Exists in an Object using Objective-C | iOS Programmer Guide

There is a simple way of testing if a method exist in an object using Objective-C. This can be achieved using the respondsToSelector method. The code snippet is given below

if ([obj respondsToSelector:@selector(methodName:withParam:)]) {
   [obj methodName:123 withParam:456];

Here, the method that we were checking if exists using objective-C is "methodName" that has two parameters.

We can also use the static message instancesRespondToSelector:(SEL)selector if you would like to call one constructor or another one depending on this. This method allows you to check before having the instance of the class. The objective-c code snippet is given below:

[MyClass instancesRespondToSelector:@selector(someMethod:withParams:)]
or like this:
[[myObject class] instancesRespondToSelector:@selector(someMethod:withParams:)]

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;

Custom Classes in Objective-C | iOS Programmer Guide

When you're defining your own classes, you should at a minimum inherit from NSObject.

If you want to define a custom button for use in an iOS app, for example, and the provided UIButton class doesn't offer enough customizable attributes to satisfy your needs, it makes more sense to create a new class inheriting from UIButton than from NSObject. If you simply inherited from NSObject, you'd need to duplicate all the complex visual interactions and communication defined by the UIButton class just to make your button behave in the way expected by the user. Furthermore, by inheriting from UIButton, your subclass automatically gains any future enhancements or bug fixes that might be applied to the internal UIButton behavior.

The UIButton class itself is defined to inherit from UIControl, which describes basic behavior common to all user interface controls on iOS. The UIControl class in turn inherits from UIView, giving it functionality common to objects that are displayed on screen. UIView inherits from UIResponder, allowing it to respond to user input such as taps, gestures or shakes. Finally, at the root of the tree, UIResponder inherits from NSObject.

Root Class Provides Base Functionality in Objective-C | iOS Programmer Guide

When an Objective-C object needs to work with an instance of another class, it is expected that the other class offers certain basic characteristics and behavior. For this reason, Objective-C defines a root class from which the vast majority of other classes inherit, called NSObject. When one object encounters another object, it expects to be able to interact using at least the basic behavior defined by the NSObject class description.

Classes Can Inherit from Other Classes in Objective-C | iOS Programmer Guide

When one class inherits from another, the child inherits all the behavior and properties defined by the parent. It also has the opportunity either to define its own additional behavior and properties, or override the behavior of the parent.

In the case of Objective-C string classes, the class description for NSMutableString specifies that the class inherits from NSString, All of the functionality provided by NSString is available in NSMutableString, such as querying specific characters or requesting new uppercase strings, but NSMutableString adds methods that allow you to append, insert, replace or delete substrings and individual characters.

What is Classes in Objective-C? | iOS Interview Question | iOS Programmer Guide

A class describes the behavior and properties common to any particular type of object. For a string object, It is an instance of the class NSString.
every instance of a class shares the same properties and behavior as all other instances of that class. Every NSString instance behaves in the same way, regardless of the internal string of characters it holds.

Some classes define objects that are immutable. This means that the internal contents must be set when an object is created, and cannot subsequently be changed by other objects. In Objective-C, all basic NSString and NSNumber objects are immutable. If you need to represent a different number, you must use a new NSNumber instance.

Some immutable classes also offer a mutable version. If you specifically need to change the contents of a string at runtime, for example by appending characters as they are received over a network connection, you can use an instance of the NSMutableString class. Instances of this class behave just like NSString objects, except that they also offer functionality to change the characters that the object represents.

Fundamentals of Objective C | iOS Programmer Guide

Objective-C is the primary programming language you use when writing software for OS X and iOS. It's a superset of the C programming language and provides object-oriented capabilities and a dynamic runtime.
Objective-C inherits the syntax, primitive types, and flow control statements of C and adds syntax for defining classes and methods.

When building apps for iOS, you'll spend most of your time working with objects. Those objects are instances of Objective-C classes, some of which are provided for you by Cocoa Touch and some of which you'll write yourself.

An app is built as a large ecosystem of interconnected objects that communicate with each other to solve specific problems, such as displaying a visual interface, responding to user input, or storing information. For iOS development, you don't need to create objects from scratch to solve every conceivable problem; instead you have a large library of existing objects available for your use, provided by Cocoa Touch for iOS.

Adding UIToolbar On Top of Keyboard in Objective-C | iOS Programmer Guide

We can add UIToolbar on top of the keyboard via code in iOS. First, create and instantiate an UIToolbar as given below:

UIToolbar *keyboardToolbar = [[UIToolbar alloc] initWithFrame: CGRectMake(0,0, 320, 44)];

Then create the required buttons to add them to the created UIToolbar. here, it is keyboardToolbar created:

UIBarButtonItem *flex = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];

UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(cancelKeyboard)];

Then add these created bar buttons to UIToolbar as below:

[keyboardToolbar setItems:[NSArray arrayWithObjects:flex, cancelButton, nil] animated:NO]; subjectTextField.inputAccessoryView = keyboardToolbar;

Now the UIToolbar is ready. Finally, let us assign this UIToolbar to the UITextField as given in the below objective-c code snippet: (Note: Consider the textField as the available UITextField)

textField.inputAccessoryView = keyboardToolbar;

Creating Forms Using UITableView and UITextField | iOS Programmer Guide

To create a form that resembles the Gmail form in the iPhone Mail application, create a UITableView and add a UITextField into each UITableViewCell.
You can download the source code for an example here:
What follows is a brief explanation of some parts of the code.

Source Explanation

Our controller class has fields to hold references to the UITextFields and their values when they are modified.
  1. @interface FormTableController : UITableViewController<UITextFieldDelegate> {  
  2.     NSString* name_ ;  
  3.     NSString* address_ ;  
  4.     NSString* password_ ;  
  5.     NSString* description_ ;      
  7.     UITextField* nameField_ ;  
  8.     UITextField* addressField_ ;  
  9.     UITextField* passwordField_ ;  
  10.     UITextField* descriptionField_ ;      
  11. }  
The makeTextField method creates a UITextField that resembles the ones used in the iPhone Mail application.
  1. -(UITextField*) makeTextField: (NSString*)text    
  2.                   placeholder: (NSString*)placeholder  {  
  3.     UITextField *tf = [[[UITextField alloc] init] autorelease];  
  4.     tf.placeholder = placeholder ;  
  5.     tf.text = text ;           
  6.     tf.autocorrectionType = UITextAutocorrectionTypeNo ;  
  7.     tf.autocapitalizationType = UITextAutocapitalizationTypeNone;  
  8.     tf.adjustsFontSizeToFitWidth = YES;  
  9.     tf.textColor = [UIColor colorWithRed:56.0f/255.0f green:84.0f/255.0f blue:135.0f/255.0f alpha:1.0f];      
  10.     return tf ;  
  11. }  
The makeTextField is then called in the cellForRowAtIndexPath method to create the text fields, which are then added as subviews of the UITableCells.
  1. cell.textLabel.text = @"Name" ;  
  2. tf = nameField_ = [self placeholder:@"John Appleseed"];  
  3. [cell addSubview:nameField_];  
The dimensions of the text field are also adjusted:
  1. // Textfield dimensions  
  2. tf.frame = CGRectMake(120, 12, 170, 30);  
When the value of any UITextField is changed, we save the new values by handling textFieldDidEndEditing.
  1. // Textfield value changed, store the new value.  
  2. - (void)textFieldDidEndEditing:(UITextField *)textField {  
  3.     if ( textField == nameField_ ) {  
  4. = textField.text ;  
  5.     } else if ( textField == addressField_ ) {  
  6.         self.address = textField.text ;  
  7.     } else if ( textField == passwordField_ ) {  
  8.         self.password = textField.text ;  
  9.     } else if ( textField == descriptionField_ ) {  
  10.         self.description = textField.text ;       
  11.     }  
  12. }  
Lastly, we dismiss the keyboard when the user taps Return by handling UIControlEventEditingDidEndOnExit.
  1. // Workaround to dismiss keyboard when Done/Return is tapped  
  2. [tf addTarget:self action:@selector(textFieldFinished:) forControlEvents:UIControlEventEditingDidEndOnExit];      
  1. // Workaround to hide keyboard when Done is tapped  
  2. - (IBAction)textFieldFinished:(id)sender {  
  3.     // [sender resignFirstResponder];  
  4. }  

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.

Adding Section and Index List in UITableView | Indexing In UITableView | iOS Programmer Guide

Let us see how to add an index list in a UITableView. An indexed table view is more or less as the plain-styled table view. The only difference is that it includes an index on the right side of the table view. Indexed table is very common in iOS apps. The most well-known example is the built-in Contacts app on iPhone. By offering an index scrolling, users are allowed to access a particular section of the table instantly without scrolling through each section.

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.

Relationship Between Superviews and Subviews in iOS | Explain View Hierarchies in iOS Application | iOS Programmer Guide

In addition to providing its own content, a view can act as a container for other views. When one view contains another, a parent-child relationship is created between the two views. The child view in the relationship is known as the subview and the parent view is known as the superview. The creation of this type of relationship has implications for both the visual appearance of your application and the application’s behavior.
Visually, the content of a subview obscures all or part of the content of its parent view. If the subview is totally opaque, then the area occupied by the subview completely obscures the corresponding area of the parent. If the subview is partially transparent, the content from the two views is blended together prior to being displayed on the screen. Each superview stores its subviews in an ordered array and the order in that array also affects the visibility of each subview. If two sibling subviews overlap each other, the one that was added last (or was moved to the end of the subview array) appears on top of the other.
The superview-subview relationship also impacts several view behaviors. Changing the size of a parent view has a ripple effect that can cause the size and position of any subviews to change too. When you change the size of a parent view, you can control the resizing behavior of each subview by configuring the view appropriately. Other changes that affect subviews include hiding a superview, changing a superview’s alpha (transparency), or applying a mathematical transform to a superview’s coordinate system.
The arrangement of views in a view hierarchy also determines how your application responds to events. When a touch occurs inside a specific view, the system sends an event object with the touch information directly to that view for handling. However, if the view does not handle a particular touch event, it can pass the event object along to its superview. If the superview does not handle the event, it passes the event object to its superview, and so on up the responder chain. Specific views can also pass the event object to an intervening responder object, such as a view controller. If no object handles the event, it eventually reaches the application object, which generally discards it

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.

Avoiding Adding Multiple NSNotification Observer | iOS Programmer Guide

There is no predefined way of detecting if an observer has already been added for a particular NSNotification. So the best way to avoid adding multiple NSNotification observers is by explicitly calling removeObserver for the target / selector before adding it again. This way we can prevent duplicate observers from being added. The below method can be added as a category method

@interface NSNotificationCenter (UniqueNotif)

- (void)addUniqueObserver:(id)observer selector:(SEL)selector name:(NSString *)name object:(id)object {

        [[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:object];
        [[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:name object:object];



This assumes that the you will only add one unique observer to each target for any notification name, as it will remove any existing observers for that notification name.