Monday, October 28, 2013

Basic Objective C Interview Question & Answer Part-1


1) What is an Objective-C?
Objective-C defines a small but powerful set of extensions to the ANSI C programming language that enables sophisticated object-oriented programming. Objective-C is the native language for Cocoa programming.

Objective-C is a very dynamic language. Its dynamism frees a program from compile-time and link-time constraints and shifts much of the responsibility for symbol resolution to runtime, when the user is in control.
Objective-C is more dynamic than other programming languages because its dynamism springs from three sources:
·       Dynamic typing—determining the class of an object at runtime
·       Dynamic binding—determining the method to invoke at runtime
·       Dynamic loading—adding new modules to a program at runtime
2) Dynamic and Static Typing.
Static typed languages are those in which type checking is done at compile-time, whereas dynamic typed languages are those in which type checking is done at run-time.
Objective-C is a dynamically typed language, meaning that you don't have to tell the compiler what type of object you're working with at compile time.
Declaring a type for a variable is merely a promise, which can be broken at runtime if the code leaves room for such a thing. You can declare your variables as type id, which is suitable for any Objective-C object.
Objective-C vs C/C++.
o   The Objective-C class allows a method and a variable with the exact same name. In C++, they must be different.
o   Objective-C does not have a constructor or destructor. Instead it has init and dealloc methods, which must be called explicitly.
o   Objective-C uses + and - to differentiate between factory and instance methods, C++ uses static to specify a factory method.
o   Multiple inheritance is not allowed in Obj-C, however we can use protocol to some extent.
o   Obj-C has runtime binding leading to dynamic linking.
o   Obj-C has got categories.
o   Objective-C has a work-around for method overloading, but none for operator overloading.
o   Objective-C also does not allow stack based objects. Each object must be a pointer to a block of 
memory.
o   In Objective-C the message overloading is faked by naming the parameters. C++ actually does the 
same thing but the compiler does the name mangling for us. In Objective-C, we have to mangle the 
names manually.
o   One of C++'s advantages and disadvantages is automatic type coercion.
o   Another feature C++ has that is missing in Objective-C is references. Because pointers can be 
used wherever a reference is used, there isn't much need for references in general.
o   Templates are another feature that C++ has that Objective-C doesn't. Templates are needed because C++ has strong typing and static binding that prevent generic classes, such as List and 
Array.

3) What are the types of accessory methods?
We have 2 types of accessor methods:
i.Getter method:

Getter method is an accessor method that retrieves the value of an instance variable.
ii.Setter method:

Setter method is an accessor method that Sets the value of an instance variable.
4) What is a Selector?
Selector can either be a name of method or message to an object.
Compiled selectors are of type SEL. There are two common ways to get a selector:

At compile time, you use the compiler directive @selector.

SEL aSelector = @selector(methodName);
At runtime, you use the NSSelectorFromString function, where the string is the name of the method:

SEL aSelector = NSSelectorFromString(@"methodName");
Using a Selector
         You can invoke a method using a selector with performSelector: and other similar methods.
   
    SEL aSelector = @selector(run);
    [aDog performSelector:aSelector];
    [anAthlete performSelector:aSelector];
    [aComputerSimulation performSelector:aSelector];

5) What is Delegate?
It is a helper object.
it is an object that usually read to some events in another object
A Delegate allows one object to send messages to another object when an Event happens.
An object directly to carryout an action by another object.
6) What are the App states. Explain them?
State
Description
Not running
The app has not been launched or was running but was terminated by the system.
Inactive
The 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.
Active
The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.
Background
The 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.
Suspended
The 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.

State changes in an iOS app


7) What is Automatic Reference Counting (ARC)?
ARC is a compiler-level feature that simplifies the process of managing the lifetimes of Objective-C objects. Instead of you having to remember when to retain or release an object, ARC evaluates the lifetime requirements of your objects and automatically inserts the appropriate method calls at compile time.

8) Class Introspection
Determine whether an objective-C object is an instance of a class
[obj isMemberOfClass:someClass];
Determine whether an objective-C object is an instance of a class or its descendants
[obj isKindOfClass:someClass];
The version of a class
[MyString version]
Find the class of an Objective-C object
Class c = [obj1 class]; Class c = [NSString class];
Verify 2 Objective-C objects are of the same class
[obj1 class] == [obj2 class]


9) Immutable vs Mutable
Immutable objects cant be changed. However they are just pointing to some location where stored values are made constant. You can change that reference to other location. Mutable objects can change the value.
10 ) What is the difference between retain & assign?
Assign creates a reference from one object to another without increasing the source’s retain count.

if (_variable != object)
{
[_variable release];
_variable = nil;
 _variable = object;
}
Retain creates a reference from one object to another and increases the retain count of the source object.

if (_variable != object)
{ [_variable release];
_variable = nil;

_variable = [object retain];
 }
11) Why do we need to use @Synthesize?
We can use generated code like nonatomic, atmoic, retain without writing any lines of code. We also have getter and setter methods. To use this, you have 2 other ways: @synthesize or @dynamic: @synthesize, compiler will generate the getter and setter automatically for you, @dynamic: you have to write them yourself.@property is really good for memory management, for example: retain.How can you do retain without @property?
if (_variable != object)
{

[_variable release];
_variable = nil;

_variable = [object retain];
}
How can you use it with @property?self.variable = object; When we are calling the above line, we actually call the setter like [self setVariable:object] and then the generated setter will do its job
12) What is categories in iOS?
You use categories to define additional methods of an existing class—even one whose source code is unavailable to you—without subclassing. You typically use a category to add methods to an existing class, such as one defined in the Cocoa frameworks. The added methods are inherited by subclasses and are indistinguishable at runtime from the original methods of the class. You can also use categories of your own classes to:
·       Distribute the implementation of your own classes into separate source files—for example, you could group the methods of a large class into several categories and put each category in a different file.
·       Declare private methods.
You add methods to a class by declaring them in an interface file under a category name and defining them in an implementation file under the same name. The category name indicates that the methods are an extension to a class declared elsewhere, not a new class.
#import "SystemClass.h"

@interface SystemClass (CategoryName)
// method declarations
@end

A common naming convention is that the base file name of the category is the name of the class the category extends followed by “+” followed by the name of the category. This category might be declared in a file named SystemClass+CategoryName.h.
Implementation:
#import "SystemClass+CategoryName.h"

@implementation SystemClass ( CategoryName )
// method definitions
@end
 13) What is Delegation in iOS?
Delegation is a design pattern in which one object sends messages to another object—
specified as its delegate—to ask for input or to notify it that an event is occurring. Delegation is often used as an alternative to class inheritance to extend the functionality of reusable objects. For example, before a window changes size, it asks its delegate whether the new size is ok. The delegate replies to the window, telling it that the suggested size is acceptable or suggesting a better size. (For more details on window resizing, see thewindowWillResize:toSize: message.)Delegate methods are typically grouped into a protocol. A protocol is basically just a list of methods. The delegate protocol specifies all the messages an object might send to its delegate. If a class conforms to (or adopts) a protocol, it guarantees that it implements the required methods of a protocol. (Protocols may also include optional methods).In this application, the application object tells its delegate that the main startup routines have finished by sending it theapplicationDidFinishLaunching: message. The delegate is then able to perform additional tasks if it wants.
14) How can we achieve singleton pattern in iOS?
The Singleton design pattern ensures a class only has one instance, and provides a global point of access to it. The class keeps track of its sole instance and ensures that no other instance can be created. Singleton classes are appropriate for situations where it makes sense for a single object to provide access to a global resource.Several Cocoa framework classes are singletons. They include NSFileManager, NSWorkspace, NSApplication, and, in UIKit, UIApplication. A process is limited to one instance of these classes. When a client asks the class for an instance, it gets a shared instance, which is lazily created upon the first request.
15) What is delegate pattern in iOS?
Delegation is a mechanism by which a host object embeds a weak reference (weak in the sense that it’s a simple pointer reference, unretained) to another object—its delegate—and periodically sends messages to the delegate when it requires its input for a task. The host object is generally an “off-the-shelf” framework object (such as an NSWindow or NSXMLParserobject) that is seeking to accomplish something, but can only do so in a generic fashion. The delegate, which is almost always an instance of a custom class, acts in coordination with the host object, supplying program-specific behavior at certain points in the task (see Figure 4-3). Thus delegation makes it possible to modify or extend the behavior of another object without the need for subclassing.Refer: delegate pattern
16) What are all the difference between categories and subclasses?Why should we go to subclasses?
Category is a feature of the Objective-C language that enables you to add methods (interface and implementation) to a class without having to make a subclass. There is no runtime difference—within the scope of your program—between the original methods of the class and the methods added by the category. The methods in the category become part of the class type and are inherited by all the class’s subclasses.As with delegation, categories are not a strict adaptation of the Decorator pattern, fulfilling the intent but taking a different path to implementing that intent. The behavior added by categories is a compile-time artifact, and is not something dynamically acquired. Moreover, categories do not encapsulate an instance of the class being extended.The Cocoa frameworks define numerous categories, most of them informal protocols . Often they use categories to group related methods. You may implement categories in your code to extend classes without subclassing or to group related methods. However, you should be aware of these caveats:
You cannot add instance variables to the class.

If you override existing methods of the class, your application may behave unpredictably.

Basic IOS interview Question & Answer

1) What is Cocoa?
Cocoa is an application environment for both the Mac OS X operating system and iOS.
It consists of a suite of object-oriented software libraries, a runtime system, and an integrated development environment.
Carbon is an alternative environment in Mac OS X, but it is a compatibility framework with procedural programmatic interfaces intended to support existing Mac OS X code bases.


2) Cocoa in the architecture of OS X
            Architecturally, OS X is a series of software layers going from the foundation of Darwin to the various application frameworks and the user experience they support.

The intervening layers represent the system software largely (but not entirely) contained in the two major umbrella frameworks, Core Services and Application Services.


In OS X, Cocoa has two core Objective-C frameworks that are essential to application development for OS X
·       Appkit (Application Kit)
·       Foundation

3) Cocoa in the architecture of iOS
            The application-framework layer of iOS is called Cocoa Touch.


Those following layers present in IOS
·       Core OS. This level contains the kernel, the file system, networking infrastructure, security, power management, and a number of device drivers. It also has the libSystem library, which supports the POSIX/BSD 4.4/C99 API specifications and includes system-level APIs for many services.
·       Core Services. The frameworks in this layer provide core services, such as string manipulation, collection management, networking, URL utilities, contact management, and preferences. They also provide services based on hardware features of a device, such as the GPS, compass, accelerometer, and gyroscope. Examples of frameworks in this layer are Core Location, Core Motion, and System Configuration.
This layer includes both Foundation and Core Foundation, frameworks that provide abstractions for common data types such as strings and collections. The Core Frameworks layer also contains Core Data, a framework for object graph management and object persistence.
·       Media. The frameworks and services in this layer depend on the Core Services layer and provide graphical and multimedia services to the Cocoa Touch layer. They include Core Graphics, Core Text, OpenGL ES, Core Animation, AVFoundation, Core Audio, and video playback.
·       Cocoa Touch. The frameworks in this layer directly support applications based in iOS. They include frameworks such as Game Kit, Map Kit, and iAd.

4) Application Kit/App kit.
The Application Kit is a framework containing all the objects you need to implement your graphical, event- driven user interface: windows, panels, buttons, menus, scrollers, and text fields.
 The Application Kit handles all the details for you as it efficiently draws on the screen, communicates with hardware devices and screen buffers, clears areas of the screen before drawing, and clips views.

You also have the choice at which level you use the Application Kit:
·       Use Interface Builder to create connections from user interface objects to your application objects.
·       Control the user interface programmatically, which requires more familiarity with AppKit classes and protocols.

·       Implement your own objects by subclassing NSView or other classes.
5) UIKit
This framework provides the objects an application displays in its user interface and defines the structure for application behavior, including event handling and drawing.

The UIKit framework in iOS is the sister framework of the AppKit framework in OS X.
One of the greatest differences is that, in iOS, the objects that appear in the user interface of a Cocoa application look and behave in a way that is different from the way their counterparts in a Cocoa application running in OS X look and behave. Some common examples are text views, table views, and buttons.

6) Foundation Kit.
The Foundation framework defines a base layer of Objective-C classes. In addition to providing a set of useful primitive object classes, it introduces several paradigms that define functionality not covered by the Objective-C language. The Foundation framework is designed with these goals in mind:
·       Provide a small set of basic utility classes.

·       Make software development easier by introducing consistent conventions for things such as deallocation.

·       Support Unicode strings, object persistence, and object distribution.
·       Provide a level of OS independence, to enhance portability.

7) What are SDK tools in iPhone?
XCode


Simulator
Instruments
8) What is Xcode?
Xcode is the engine that powers Apple’s integrated development environment (IDE) for OS X and iOS. Xcode builds projects from source code written in C, C++, Objective-C, and Objective-C++. It allows you to:
·       Create and manage projects, including specifying platforms, target requirements, dependencies, and build configurations.
·       Write source code in editors with features such as syntax coloring and automatic indenting.
·       Navigate and search through the components of a project, including header files and documentation.
·       Build the project.
·       Debug the project locally, in iOS Simulator, or remotely, in a graphical source-level debugger.
9) What is the simulator?
For iOS projects, you can select iOS Simulator as the platform SDK for the project. When you build and run the project, Xcode runs Simulator, which presents your application as it would appear on the device (iPhone or iPad) and allows you to manipulate parts of the user interface. You can use Simulator to help you debug the application prior to loading it onto the device.

10) what are Instruments?
Instruments is an application introduced in Xcode 3.0 that lets you run multiple performance-testing tools simultaneously and view the results in a timeline-based graphical presentation.
It can show you CPU usage, disk reads and writes, memory statistics, thread activity, garbage collection, network statistics, directory and file usage, and other measurements—individually or in different combinations—in the form of graphs tied to time.
This simultaneous presentation of instrumentation data helps you to discover the relationships between what is being measured. It also displays the specific data behind the graphs.

No need to install on your mac. Already Xcode contains instruments.


11) What is Interface Builder?
Interface Builder is a graphical tool for creating user interfaces.
Interface Builder is centered around four main design elements:
Nib files. A nib file is a file wrapper that contains the objects appearing on a user interface in an archived form.
Nib files offer a way to easily localize user interfaces. Interface Builder stores a nib file in a localized directory inside a Cocoa project; when that project is built, the nib file is copied to a corresponding localized directory in the created bundle.
Explain about Inspector
It is mainly used for setting the properties of view elements.
It contains four sections.
  1. File Inspector
  2. Quick Help Inspector
  3. Identity Inspector
  4. Attribute Inspector
  5. Size Inspector
  6. Connection Inspector