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.)
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.
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!
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 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.
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.)
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).
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.
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:
*Q: What are all the newly added frameworks iOS 4.3 to iOS 5.0?
A:
- • Accounts
- • CoreBluetooth
- • CoreImage
- • GLKit
- • GSS
- • NewsstandKit
*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 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
*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.
ThankQ
By Praveen