Search Posts in my Blog

Showing posts with label objective C question and answer. Show all posts
Showing posts with label objective C question and answer. Show all posts

Monday, 9 July 2012

iOS Interview Questions - Part 2


Difference between shallow copy and deep copy?

Ans: Shallow copy is also known as address copy. In this process you only copy address not actual data while in deep copy you copy data.
Suppose there are two objects A and B. A is pointing to a different array while B is pointing to different array. Now what I will do is following to do shallow copy.
Char *A = {‘a’,’b’,’c’};
Char *B = {‘x’,’y’,’z’};
B = A;
Now B is pointing is at same location where A pointer is pointing.Both A and B in this case sharing same data. if change is made both will get altered value of data.Advantage is that coping process is very fast and is independent of size of array.
while in deep copy data is also copied. This process is slow but Both A and B have their own copies and changes made to any copy, other will copy will not be affected.

What is advantage of categories? What is difference between implementing a category and inheritance? 

Ans: You can add method to existing class even to that class whose source is not available to you. You can extend functionality of a class without subclassing. You can split implementation in multiple classes. While in Inheritance you subclass from parent class and extend its functionality.

Difference between categories and extensions?

Ans:Class extensions are similar to categories. The main difference is that with an extension, the compiler will expect you to implement the methods within your main @implementation, whereas with a category you have a separate @implementation block. So you should pretty much only use an extension at the top of your main .m file (the only place you should care about ivars, incidentally) — it’s meant to be just that, an extension.

What are KVO and KVC?KVC: Normally instance variables are accessed through properties or accessors but KVC gives another way to access variables in form of strings. In this way your class acts like a dictionary and your property name for example “age” becomes key and value that property holds becomes value for that key. For example, you have employee class with name property.
You access property like
NSString age = emp.age;
setting property value.
emp.age = @”20″;
Now how KVC works is like this
[emp valueForKey:@"age"];
[emp setValue:@"25" forKey:@"age"];
KVO : The mechanism through which objects are notified when there is change in any of property is called KVO.
For example, person object is interested in getting notification when accountBalance property is changed in BankAccount object.To achieve this, Person Object must register as an observer of the BankAccount’s accountBalance property by sending an addObserver:forKeyPath:options:context: message.

Can we use two tableview controllers on one view controller?

Ans: Yes, we can use two tableviews on the same view controllers and you can differentiate between two by assigning them tags…or you can also check them by comparing their memory addresses.

What is keyword atomic in Objective C?

Ans: When you place keyword atomic with a property, it means at one time only one thread can access it.


What are mutable and immutable types in Objective C?

Ans: Mutable means you can change its contents later but when you mark any object immutable, it means once they are initialized, their values cannot be changed. For example, NSArray, NSString values cannot be changed after initialized.

When we call objective c is runtime language what does it mean?
Ans: Objective-C runtime is runtime library that is open source that you can download and understand how it works. This library is written in C and adds object-oriented capabilities to C and makes it objective-c. It is only because of objective c runtime that it is legal to send messages to objects to which they don’t know how to respond to. Methods are not bound to implementation until runtime. Objective-C defers its decisions from compile time to run time as much as it can. For example, at runtime, it can decide to which object it will send message or function.

What is difference between NSNotification and delegate?
Ans:Delegate is passing message from one object to other object. It is like one to one communication while nsnotification is like passing message to multiple objects at the same time. All other objects that have subscribed to that notification or acting observers to that notification can or can’t respond to that event. Notifications are easier but you can get into trouble by using those like bad architecture. Delegates are more frequently used and are used with help of protocols.

Swap the two variable values without taking third variable?

Ans:-
int x=10;
int y=5;
x=x+y;
NSLog(@”x==> %d”,x);
y=x-y;
NSLog(@”Y Value==> %d”,y);
x=x-y;
NSLog(@”x Value==> %d”,x);

What is push notification?
Imagine, you are looking for a job. You go to software company daily and ask sir “is there any job for me” and they keep on saying no.  Your time and money is wasted on each trip.(Pull Request mechanism)
So, one day owner says, if there is any suitable job for you, I will let you know. In this mechanism, your time and money is not wasted. (Push Mechanism)

How it works?
This service is provided by Apple in which rather than pinging server after specific interval for data which is also called pull mechanism, server will send notification to your device that there is new piece of information for you. Request is initiated by server not the device or client.

Flow of push notification
Your web server sends message (device token + payload) to Apple push notification service (APNS) , then APNS routes this message to device whose device token specified in notification.

What is polymorphism?
This is very famous question and every interviewer asks this. Few people say polymorphism means multiple forms and they start giving example of draw function which is right to some extent but interviewer is looking for more detailed answer.
Ability of base class pointer to call function from derived class at runtime is called polymorphism.
For example, there is super class human and there are two subclasses software engineer and hardware engineer. Now super class human can hold reference to any of subclass because software engineer is kind of human. Suppose there is speak function in super class and every subclass has also speak function. So at runtime, super class reference is pointing to whatever subclass, speak function will be called of that class. I hope I am able to make you understand.

What is responder chain?
Ans: Suppose you have a hierarchy of views such like  there is superview A which have subview B and B has a subview C. Now you touch on inner most view C. The system will send touch event to subview C for handling this event. If C View does not want to handle this event, this event will be passed to its superview B (next responder). If B also does not want to handle this touch event it will pass on to superview A. All the view which can respond to touch events are called responder chain. A view can also pass its events to uiviewcontroller. If view controller also does not want to respond to touch event, it is passed to application object which discards this event.
Apple responder chain
Apple responder chain

iOS Interview Questions - Part 1

I’ve been interviewing alot of people recently for iPhone and iPad developer positions. Asides from algorithm runtime problems, I ask some general iOS questions. So being the kind person I am posting some questions based on difficulty and expected answers.






BEGINNER
  • Q: How would you create your own custom view?
    A: Subclass the UIView class.

  • Q: Whats fast enumeration?
    A: Fast enumeration is a language feature that allows you to enumerate over the contents of a collection. (Your code will also run faster because the internal implementation reduces message send overhead and increases pipelining potential.)

  • Q: Whats a struct?
    A: A struct is a special C data type that encapsulates other pieces of data into a single cohesive unit. Like an object, but built into C.

  • Q: Whats the difference between a NSArray and a NSMutableArray?
    A: A NSArray’s contents can not be modified once it’s been created whereas a NSMutableArray can be modified as needed, i.e items can be added/removed from it.

  • Q: Explain retain counts.
    A: Retain counts are the way in which memory is managed in Objective-C. When you create an object, it has a retain count of 1. When you send an object a retain message, its retain count is incremented by 1.
    When you send an object a release message, its retain count is decremented by 1. When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future. If an object’s retain count is reduced to 0, it is deallocated.

  • Q: Whats the difference between frame and bounds?
    A: The frame of a view is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.
    The bounds of a view is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).

  • Q: Is a delegate retained?
    A: No, the delegate is never retained! Ever!

INTERMEDIATE
  • Q: If I call performSelector:withObject:afterDelay: – is the object retained?
    A: Yes the object is retained. It creates a timer that calls a selector on the current threads run loop. It may not be 100% precise time-wise as it attempts to dequeue the message from the run loop and perform the selector.

  • Q: Can you explain what happens when you call autorelease on an object?
    A: When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future. The object is added to an autorelease pool on the current thread. The main thread loop creates an autorelease pool at the beginning of the function, and release it at the end. This establishes a pool for the lifetime of the task. However, this also means that any autoreleased objects created during the lifetime of the task are not disposed of until the task completes. This may lead to the task’s memory footprint increasing unnecessarily. You can also consider creating pools with a narrower scope or use NSOperationQueue with it’s own autorelease pool. (Also important – You only release or autorelease objects you own.)

  • Q: Whats the NSCoder class used for?
    A: NSCoder is an abstractClass which represents a stream of data. They are used in Archiving and Unarchiving objects. NSCoder objects are usually used in a method that is being implemented so that the class conforms to the protocol. (which has something like encodeObject and decodeObject methods in them).

  • Q: Whats an NSOperationQueue and how/would you use it?
    A: The NSOperationQueue class regulates the execution of a set of NSOperation objects. An operation queue is generally used to perform some asynchronous operations on a background thread so as not to block the main thread.

  • Q: Explain the correct way to manage Outlets memory
    A: Create them as properties in the header that are retained. In the viewDidUnload set the outlets to nil(i.e self.outlet = nil). Finally in dealloc make sure to release the outlet.

ADVANCED
  • Q: Is the delegate for a CAAnimation retained?
    A: Yes it is!! This is one of the rare exceptions to memory management rules.

  • Q: What happens when the following code executes?
    1Ball *ball = [[[[Ball alloc] init] autorelease] autorelease];
    A: It will crash because it’s added twice to the autorelease pool and when it it dequeued the autorelease pool calls release more than once.


  • Q: Outline the class hierarchy for a UIButton until NSObject.
    A: UIButton inherits from UIControl, UIControl inherits from UIView, UIView inherits from UIResponder, UIResponder inherits from the root class NSObject

  • Q: Explain the difference between NSOperationQueue concurrent and non-concurrent.
    A: In the context of an NSOperation object, which runs in an NSOperationQueue, the terms concurrent and non-concurrent do not necessarily refer to the side-by-side execution of threads. Instead, a non-concurrent operation is one that executes using the environment that is provided for it while a concurrent operation is responsible for setting up its own execution environment.

  • Q: Implement your own synthesized methods for the property NSString *title.
    A: Well you would want to implement the getter and setter for the title object. Something like this:
    1- (NSString*) title {
    2  return title;
    3}
    4- (void) setTitle: (NSString*) newTitle {
    5 if (newTitle != title) {
    6     [title release];
    7     title = [newTitle retain]; // Or copy, depending on your needs.
    8 }
    9}

  • Q: Implement the following methods: retain, release, autorelease.
    A:
    01-(id)retain {
    02  NSIncrementExtraRefCount(self);
    03
    04  return self;
    05}
    06
    07-(void)release {
    08
    09  if(NSDecrementExtraRefCountWasZero(self)) {
    10    NSDeallocateObject(self);
    11  }
    12}
    13
    14-(id)autorelease {
    15  // Add the object to the autorelease pool
    16  [NSAutoreleasePool addObject:self];
    17
    18  return self;
    19}

Hopefully some of these questions will help someone get a job! :)