Saturday, August 11, 2012

Iphone Interview Basic Questions.....

What is iPhone? 

  • IPhone is a combination of internet and multimedia enabled smart phone developed by Apple Inc.
  • iPhone functions as a camera phone, including text messaging, and visual voice mail
  • iPhone is a portable media player that resembles a video iPod
  • It has user interface that is built around the multi-touch screen including virtual keyboard.
  • App Store , which launched in the mid 2008 has over 1,00,000 applications with functionalities including games, references, GPS navigation, advertising, television shows, films, reference, celebrities. 

What is iphone OS? 

iPhone OS runs on iPhone and iPod touch devices.
Hardware devices are managed by iPhone OS and provides the technologies needed for implementing native applications on the phone.
The OS ships with several system applications such as Mail, Safari, Phone, which provide standard services to the user. 

What is iphone sdk? 

iPhone SDK is available with tools and interfaces needed for developing, installing and running custom native applications.
Native applications are built using the iPhone OS’s system frameworks and Objective-C language and run directly on iPhone OS.
Native applications are installed physically on a device and can run in presence or absence of network connection. 



Difference Between @synthesize and @dynamic




//@synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass)
//@dynamic e.g. with subclasses of NSManagedObject (CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet:

//Super class:
@property (nonatomic, retain) NSButton *someButton;
@synthesize someButton;

//Subclass:
@property (nonatomic, retain) IBOutlet NSButton *someButton;
@dynamic someButton;

Convert NSString to NSDate

NSString *dateString = @”03-Sep-11″;
    NSDateFormatter *dateFormatter = [[[NSDateFormatteralloc] init]   autorelease];
    dateFormatter.dateFormat = @”dd-MMM-yy”;
    NSDate *date = [dateFormatter dateFromString:dateString];




1. What is @interface?
- It’s a keyword used to declare the Class.


2. What is @implementation?
- It’s a keyword used to define the Class.


3. Garbage collector in iPhone?
- iOS 5.0 has got the ARC ( Automated reference counting ).  Objective C does not have a garbage collector rather it uses the reference counting algorithm to manage the memory. This was the developers task until Apple launched iOS 5.0. Again if you are targeting iOS 4.0 or earlier , ARC is no more a choice for you .

4. What is delegate?
- Delegate is an object that handles the events happening on an object. To do that delegate has to follow a protocol specifying the task it is going to handle .


5. What is @synthesize?
- We use @synthesize to generate getters and setters automatically from compiler.  We declare properties and then generate getter and setter method by using @synthesize.


6. What are the features of iOS 5.0 ?
- https://developer.apple.com/technologies/ios5/


7. What is nonatomic ?
- nonatomic and atomic are related to multithreading environment .
 - If a property has an attribute as “nonatomic” that means multiple threads can modify that property concurrently.
- If the attribute is “atomic”, the threads would be given access atomically.
-  So “Atomic” is thread safe while “nonatomic” is thread unsafe.
- Atomic drastically hampers the performance so until and unless not needed you should never go for atomic attribute. ‘nonatomic ’ will do in most of the cases.


8. What are the delegate methods of MKMapView ?
- Check the MKMapViewDelegate in the Documentation. If you don’t have Xcode with you then search on Google.


9. What are the important delegate methods of NSXML parser?

-DidStartElement
-FoundCharecters
-DidEndElement
-FoundError



10. What is @dynamic and any place where it is used ?
- It tells compiler that getter and setter are not implemented by the class but by some other class .
- May be super class or child class .

Example – Core Data
-       The Managed object classes have properties defined by using @dynamic.


11. What is @property?
- It is a keyword used to declare a property.

12. What is data source?
- The datasource is an object that implements the required datasource protocol that is needed to create a complex control.
Ex UITableView is a view that needs a datasource object to which will help building the table. Often it’s the controller that is displaying the table view. The protocol that dataSource object ( mostly controller it self) has to implement is “UITableViewDataSource” .

13. What is model view controller?
- MVC is a Design pattern .
Model stands for the database  object which will manage all the database transaction .
- View stands for the UI i.e. the UI visible to the user. User will be interacting with the view.
- Controller is an object who handles the view events and also render the database changes to the UI. In short , it bridges the interaction between Modal and View.



14. what is @ protocol?
- @protocol is a keyword used to define a protocol. A protocol is a set of method declarations defining specific purpose. It only lists out the methods prototype , the actual implantation would be provided by the class that implements /  follows the protocol.


15. what is id?
- id is a generic reference type. The variable declared using id data-type can hold any object. Most of the methods that returns an object has ‘id’ as return type. Ex – init.

16. Explain memory management?
- Most of the object oriented languages have the Garbage Collector .  All the objects are allocated on the heap memory. The Garbage Collector is a thread that runs periodically to check all the objects, which are no more being referenced from the program. Garbage collector then de-allocates all these unreferenced objects on the Heap. In this environment programmer does not need to worry about de-allocating the objects explicitly.

In Objective – C we don’t have garbage collector. ( Note: Its available from iOS 5.0 only). So in this environment we have to explicitly take care of allocation and deallocation of all the objects in our program.  And to manage this Objective C uses ‘reference counting’ algorithm as the memory management algorithm. 

Reference Counting: In this algorithm every object keeps track of it owners ( I,e reference variables from the program ) . No of owners is represented by the property retainCount declared in NSObject. If this retainCount goes to ‘0’ the object gets deallocated automatically.  We never call dealloc method on any object explicitly.


17. what is retain and release?
- retain and release are two method defined in NSObject . - -
- These methods are related to Memory Mangement .
- retain method when called increases the retainCount by 1.
- release method when called decreases the retainCount by 1


18. what is dealloc?
- dealloc method is called on an object to actually deallocate the memory for that object. ( We should never call dealloc directly )
- In reference counting environment when retainCount of an object reaches to ‘0’, the dealloc method is called on that object automatically to delete the memory space of the object .
- If the object is having some reference type variable holding other objects, then we should call release method on every variable in dealloc.
- If you override then [super dealloc] should be the last line in this method.


19. What is Autorelease pool?
-  Autorelease pool is like a container that holds the autoreleased objects .
- This pool is drained with every run-loop of the Application
- When the pool gets drained, autorelease pool sends a release message to all the objects it was holding.



20. What is Foundation Framework? Can you explain some classes from that?
- Foundation is one of the important frameworks in COCOA Touch.
- It contains the classes like  NSArray , NSString , NSObject etc .


21. What is the difference between NSArray and NSMutableArray?

* NSArray
-        is a static array
-       Once created you can not modify the array
-       Ex you can not add or remove the object in NSArray.

* NSMutableArray
-       is a dynamic array
-       You can add or remove the object dynamically.


22. Write a delegate method of the table view?
 - (void)tableView:( UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath


23. What are the delegate methods of NSURLConection?
- didReceiveResponse:
- didReceiveData:
- didFinishLoadingData:
- didFailWithError:


24. What is cocoa ?
- COCOA is a collection of frameworks used to write Applications for MAC OS X.


25. Singleton classes
- A singleton class is such a class from which no more that one instance can be created. So there will always be single instance created throughout the program.
Ex UIApplication.









iOS Questions for Beginers


* Q: How would you create your own custom view?

A:
By Subclassing 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  NSArray and  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!

iOS Questions  for Intermediate level


* 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.

iOS Questions Expert level


* 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?

 Ball *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: view source print?
 - (NSString*) title
{
     return title;
}
- (void) setTitle: (NSString*) newTitle
{
  if (newTitle != title)
  {
     [title release];
    title = [newTitle retain]; // Or copy, depending on your needs.
  }
}

* Q: Implement the following methods: retain, release, autorelease.

A:
-(id)retain
{
    NSIncrementExtraRefCount(self);
    return self;
}

-(void)release
 {
    if(NSDecrementExtraRefCountWasZero(self))
    {
         NSDeallocateObject(self);
    }
}

-(id)autorelease
 {  // Add the object to the autorelease pool
    [NSAutoreleasePool addObject:self];
    return self;
}

*Q: Explain the steps involved in submitting the App to App-Store.

A:
Ref: https://developer.apple.com/appstore/resources/approval/guidelines.html

*Q: What are all  the newly added frameworks iOS 4.3 to iOS 5.0?

A:
  • • Accounts
  • • CoreBluetooth
  • • CoreImage
  • • GLKit
  • • GSS
  • • NewsstandKit
  • • Twitter

  *Q: What are the App states. Explain them?

A:
  • Not running State:  The app has not been launched or was running but was terminated by the system.
  • Inactive state: 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. The only time it stays inactive for any period of time is when the user locks the screen or the system prompts the user to respond to some event, such as an incoming phone call or SMS message.
  • Active state: The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.
  • Background state:  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. For information about how to execute code while in the background, see “Background Execution and Multitasking.”
  • Suspended state: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.

*Q:  Explain the options and bars available in xcode 4.2/4.0 workspace window ?

A:

*Q: What is Automatic Reference Counting (ARC) ?

A:
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.

*Q: Multitasking support is available from which version?

A:
iOS 4.0

*Q: How many bytes we can send to apple push notification server.

A:
256bytes.

*Q: Can you just explain about memory management in iOS?

A:
Refer: iOS Memory Management

*Q: What is the difference between retain & assign?

A:
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];   }

*Q: Why do we need to use @Synthesize?

A:
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

*Q: What is categories in iOS?

A:
A 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.
Refer: Categories and Extensions

*Q: What is Delegation in iOS?

A:
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 the windowWillResize: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 the applicationDidFinishLaunching: message. The delegate is then able to perform additional tasks if it wants.

*Q: How can we achieve singleton pattern in iOS?

A:
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.
Refer: Singleton Pattren

*Q: What is delegate pattern in iOS?

A:
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 NSXMLParser object) 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

*Q: What are all the difference between categories and subclasses? Why should we go to subclasses?

A:
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.

*Q: What is notification in iOS?

A:
The notification mechanism of Cocoa implements one-to-many broadcast of messages based on the Observer pattern. Objects in a program add themselves or other objects to a list of observers of one or more notifications, each of which is identified by a global string (the notification name). The object that wants to notify other objects—the observed object—creates a notification object and posts it to a notification center. The notification center determines the observers of a particular notification and sends the notification to them via a message. The methods invoked by the notification message must conform to a certain single-parameter signature. The parameter of the method is the notification object, which contains the notification name, the observed object, and a dictionary containing any supplemental information.
Posting a notification is a synchronous procedure. The posting object doesn’t regain control until the notification center has broadcast the notification to all observers. For asynchronous behavior, you can put the notification in a notification queue; control returns immediately to the posting object and the notification center broadcasts the notification when it reaches the top of the queue.
Regular notifications—that is, those broadcast by the notification center—are intraprocess only. If you want to broadcast notifications to other processes, you can use the istributed notification center and its related API.

*Q: What is the difference between delegates and notifications?

A:
We can use notifications for a variety of reasons. For example, you could broadcast a notification to change how user-interface elements display information based on a certain event elsewhere in the program. Or you could use notifications as a way to ensure that objects in a document save their state before the document window is closed. The general purpose of notifications is to inform other objects of program events so they can respond appropriately.
But objects receiving notifications can react only after the event has occurred. This is a significant difference from delegation. The delegate is given a chance to reject or modify the operation proposed by the delegating object. Observing objects, on the other hand, cannot directly affect an impending operation.









@property

Just as there are two parts to a class (interface and implementation) there are also two parts to this shortcut. The first part, @property, is the part associated with the interface. The format is @property (attributes) type name; where attributes are optionally included from the list below, type is the variable type being declared, and the name is the name of the variable. Going back to our car’s implementation, we previously had something like this:


1
2
3
4
5
6
7
8
9
10
11
12 @interface Car : NSObject
{
    NSString *color;
    int location;
}

-(void) moveCarFwd: (int) feet;
-(void) moveCarBkwd: (int) feet;
-(void) setLocation: (int) where;
-(int) getLocation;

@end

Using the @property syntax we could replace -(void)
setLocation: (int) where; and -(int) getLocation;
with @property int location; Nice, eh? Keep in mind that
all we are doing is replacing the method prototypes in the interface
— to create the necessary implementation code to implement the
methods we will use @synthesize, discussed below.
Before we continue, lets step back and think about what @property is actually doing. @property and @synthesize are what are known as preprocessor macros, which is to say that when you hit “Build and Run” in xcode it knows to replace @property with some prewritten/preformatted block of code. In this case, the code it is inserting looks like this:





1
2 -(int) location;
-(void) setLocation: (int) where;




Notice that while similar to what we had written before, the ‘getter’ is now named location rather than getLocation. In other words, while we had previously used [newCar getLocation] to get the location of our car we now have to use [newCar location]. This will require us to rewrite the two NSLog lines in our example.
But what if we  wanted to keep it named getLocation? Easy. We add an attribute to the @property call. @property(getter=getLocation) int location; Here are some other attributes you can use:

getter=getterName Specifies the name of the ‘get’ method. IE -- getLocation setter=setterName Specifies the name of the ‘set’ method. IE -- setLocation readwrite Default behavior. This specifies that both a getter and a setter will be created. Mutually exclusive with readwrite. readonly Specifies that only a getter will be created. Mutually exclusive with readwrite. assign Default behavior. Specifies that the setter uses simple assignment. (IE location = where;) retain Similar to assign, but increments the reference count. Mutually exclusive with assign and copy. We will discuss this later, when we discuss memory management. copy Specifies that a copy of the object should be used for assignment. Mutually exclusive with assign and retain. We will discuss this later, when we discuss memory management. nonatomic Specifies that accessors are non-atomic. This has to do with multiprocessor environments. We’re typically going to want to have our items be atomic, which doesn’t require we specify anything (atomic is the default behavior)






That’s pretty much it. Keep this table in the back of your mind — we’ll refer back to it often.



@synthesize

Once we’ve declared the properties, we need to actually add the code to implement our methods. The only thing we accomplished by using our property implemented as @property int location; was to tell the compiler to expect us to write a Location and setLocation method in our implementation section. As a result, we have one of two options for fulfilling the compiler’s wishes:
Option 1:


1
2
3
4
5
6
7
8
9 -(void) setLocation: (int) where
{
    location = where;
}

-(int) Location
{
    return location;
}




Option 2:


1 @synthesize location;




I’ll let you guess which one I prefer. What @synthesize does is tell the precompiler that it should generate the code in option 1 for you. And that makes for a happy programmer.


What is a “delegate” in Objective C's iPhone development?

A delegate allows one object to send messages to another object when an event happens. For example, if you're downloading data from a web site asynchronously using the NSURLConnection class. NSURLConnection has three common delegates:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
ne or more of these delegates will get called when NSURLConnection encounters a failure, finishes successfully, or received a response from the web site, respectively.
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.
A good example is UIAlertView. You create a UIAlertView object to show a short message box to users, possibly giving them a choice with two buttons like "OK" and "Cancel". The UIAlertView needs a way to call you back, but it has no information of which object to call back and what method to call.
To solve this problem, you can send your self pointer to UIAlertView as a delegate object, and in exchange you agree (by declaring the UIAlertViewDelegate in your object's header file) to implement some methods that UIAlertView can call, such as alertView:clickedButtonAtIndex:.

what is the difference between xib and nib files?



nib stands for "NeXT Interface Builder",
whereas xib is for "Mac OS X Interface Builder".
Also when you compile your project, .xib file will get compiled into nib.
XIBs are flat files rather than being a bundle. This makes it easier for SCM systems to deal with. When you compile your app, the XIB is compiled into a NIB file for inclusion in your app.
The compiled NIB that is included in the app bundle is no longer editable in Interface Builder and is much smaller than the equivalent XIB or legacy NIB file.



I'm declaring an NSString property in a class and objective-c is complaining that:
difference between assign, retain and copy in terms of normal C memory management functions?

assign: In your setter method for the property, there is a simple assignment of your instance variable to the new value, eg:
- (void)setString:(NSString*)newString
{
    string = newString;
}
This can cause problems since Objective-C objects use reference counting, and therefore by not retaining the object, there is a chance that the string could be deallocated whilst you are still using it.
  • retain: this retains the new value in your setter method. For example:
- (void)setString:(NSString*)newString
{
    [newString retain];
    [string release];
    string = newString;
}
This is safer, since you explicitly state that you want to maintain a reference of the object, and you must release it before it will be deallocated.
  • copy: this makes a copy of the string in your setter method:
- (void)setString:(NSString*)newString
{
    if(string!=newString)
    {
        [string release];
        string = [newString copy];
    }
}
This is often used with strings, since making a copy of the original object ensures that it is not changed whilst you are using it.


Using NSURLConnection




NSURLConnection provides the most flexible method of downloading the contents of a URL. It provides a simple interface for creating and canceling a connection, and supports a collection of delegate methods that provide feedback and control of many aspects of the connection. These classes fall into five categories: URL loading, cache management, authentication and credentials, cookie storage, and protocol support.

Creating a Connection

In order to download the contents of a URL, an application needs to provide a delegate object that, at a minimum, implements the following delegate methods: connection:didReceiveResponse:, connection:didReceiveData:, connection:didFailWithError: and connectionDidFinishLoading:.
The example in Listing 1 initiates a connection for a URL. It begins by creating an NSURLRequest instance for the URL, specifying the cache access policy and the timeout interval for the connection. It then creates an NSURLConnection instance, specifying the request and a delegate. If NSURLConnection can’t create a connection for the request, initWithRequest:delegate: returns nil. If the connection is successful, an instance of NSMutableData is created to store the data that is provided to the delegate incrementally.
Listing 1  Creating a connection using NSURLConnection

// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                    timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData to hold the received data.
    // receivedData is an instance variable declared elsewhere.
    receivedData = [[NSMutableData data] retain];
} else {
    // Inform the user that the connection failed.
}
The download starts immediately upon receiving the initWithRequest:delegate: message. It can be canceled any time before the delegate receives a connectionDidFinishLoading: or connection:didFailWithError: message by sending the connection a cancel message.
When the server has provided sufficient data to create an NSURLResponse object, the delegate receives a connection:didReceiveResponse: message. The delegate method can examine the provided NSURLResponse and determine the expected content length of the data, MIME type, suggested filename and other metadata provided by the server.
You should be prepared for your delegate to receive the connection:didReceiveResponse: message multiple times for a single connection. This message can be sent due to server redirects, or in rare cases multi-part MIME documents. Each time the delegate receives the connection:didReceiveResponse: message, it should reset any progress indication and discard all previously received data. The example implementation in Listing 2 simply resets the length of the received data to 0 each time it is called.
Listing 2  Example connection:didReceiveResponse: implementation

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.
 
    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
 
    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
}
The delegate is periodically sent connection:didReceiveData: messages as the data is received. The delegate implementation is responsible for storing the newly received data. In the example implementation in Listing 3, the new data is appended to the NSMutableData object created in Listing 1.
Listing 3  Example connection:didReceiveData: implementation

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}
You can also use the connection:didReceiveData: method to provide an indication of the connection’s progress to the user.
If an error is encountered during the download, the delegate receives a connection:didFailWithError: message. The NSError object passed as the parameter specifies the details of the error. It also provides the URL of the request that failed in the user info dictionary using the key NSURLErrorFailingURLStringErrorKey.
After the delegate receives a message connection:didFailWithError:, it receives no further delegate messages for the specified connection.
The example in Listing 4 releases the connection, as well as any received data, and logs the error.
Listing 4  Example connectionDidFailWithError: implementation

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];
 
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
Finally, if the connection succeeds in downloading the request, the delegate receives the connectionDidFinishLoading: message. The delegate will receive no further messages for the connection and the NSURLConnection object can be released.
The example implementation in Listing 5 logs the length of the received data and releases both the connection object and the received data.
Listing 5  Example connectionDidFinishLoading: implementation

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
 
    // release the connection, and the data object
    [connection release];
    [receivedData release];
}
This represents the simplest implementation of a client using NSURLConnection. Additional delegate methods provide the ability to customize the handling of server redirects, authorization requests and caching of the response.

Controlling Response Caching

By default the data for a connection is cached according to the support provided by the NSURLProtocol subclass that handles the request. An NSURLConnection delegate can further refine that behavior by implementing connection:willCacheResponse:.
This delegate method can examine the provided NSCachedURLResponse object and change how the response is cached, for example restricting its storage to memory only or preventing it from being cached altogether. It is also possible to insert objects in an NSCachedURLResponse’s user info dictionary, causing them to be stored in the cache as part of the response.
Note: The delegate receives connection:willCacheResponse: messages only for protocols that support caching.
The example in Listing 6 prevents the caching of https responses. It also adds the current date to the user info dictionary for responses that are cached.
Listing 6  Example connection:withCacheResponse: implementation

-(NSCachedURLResponse *)connection:(NSURLConnection *)connection
                 willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    NSCachedURLResponse *newCachedResponse = cachedResponse;
 
    if ([[[[cachedResponse response] URL] scheme] isEqual:@"https"]) {
        newCachedResponse = nil;
    } else {
        NSDictionary *newUserInfo;
        newUserInfo = [NSDictionary dictionaryWithObject:[NSCalendarDate date]
                                                 forKey:@"Cached Date"];
        newCachedResponse = [[[NSCachedURLResponse alloc]
                                initWithResponse:[cachedResponse response]
                                    data:[cachedResponse data]
                                    userInfo:newUserInfo
                                    storagePolicy:[cachedResponse storagePolicy]]
                            autorelease];
    }
    return newCachedResponse;
}

Estimating Upload Progress

You can estimate the progress of an HTTP POST upload with the connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite: delegate method. Note that this is not an exact measurement of upload progress, because the connection may fail or the connection may encounter an authentication challenge.

Downloading Data Synchronously

NSURLConnection provides support for downloading the contents of an NSURLRequest in a synchronous manner using the class method sendSynchronousRequest:returningResponse:error:. Using this method is not recommended, because it has severe limitations:
  • The client application blocks until the data has been completely received, an error is encountered, or the request times out.
  • Minimal support is provided for requests that require authentication.
  • There is no means of modifying the default behavior of response caching or accepting server redirects.
If the download succeeds, the contents of the request are returned as an NSData object and an NSURLResponse for the request is returned by reference. If NSURLConnection is unable to download the URL, the method returns nil and any available NSError instance by reference in the appropriate parameter.
If the request requires authentication in order to make the connection, valid credentials must already be available in the NSURLCredentialStorage, or must be provided as part of the requested URL. If the credentials are not available or fail to authenticate, the URL loading system responds by sending the NSURLProtocol subclass handling the connection a continueWithoutCredentialForAuthenticationChallenge: message.
When a synchronous connection attempt encounters a server redirect, the redirect is always honored. Likewise the response data is stored in the cache according to the default support provided by the protocol implementation.



1. viewDidLoad

Called after the controller’s view is loaded into memory.
- (void)viewDidLoad
Discussion
This method is called after the view controller has loaded its view hierarchy into memory. This method is called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the loadView method. You usually override this method to perform additional initialization on views that were loaded from nib fil
viewDidLoad: Alerts you that a view has finished loading



2. viewWillAppear:

Notifies the view controller that its view is about to be added to a view hierarchy.
- (void)viewWillAppear:(BOOL)animated
Parameters
animated
If YES, the view is being added to the window using an animation.
Discussion
This method is called before the receiver’s view is about to be added to a view hierarchy and before any animations are configured for showing the view. You can override this method to perform custom tasks associated with displaying the view. For example, you might use this method to change the orientation or style of the status bar to coordinate with the orientation or style of the view being presented. If you override this method, you must call super at some point in your implementation.



viewWillAppear: Runs just before the view loads








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.
Difference between protocol in objective c and interfaces in java?
Ans:Protocol is also way to relate classes that are not related in inheritance hierarchy. Protocols and interfaces both are used to achieve multiple inheritance.
There is minor difference between these two. In Objective-C, protocols also implement NSObject protocol to access all the mehthods in NSObject
@protocol WebProtocol <NSObject>
@end
If I don’t implement NSObject explicitly, I will not be able to access NSObject methods like retain, release etc. when I access through WebProtocol instance.
While in Java you don’t need to implement Object interface explicitly. It is implicitly implemented.
This link will help you. Thanks to Tom Jefferys.
http://stackoverflow.com/questions/990360/differences-between-java-interfaces-and-objective-c-protocols
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);
Thanks to Subrat for answering this question.
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.


No comments:

Post a Comment