60 Interview Questions
Every iOS Developer Should Know. (Part 1)
In this first blog post i have tried to cover simple questions on ObjectiveC. Answers for all questions has been collected from multiple sources. If you have better answer for any of the question below please send it as a comment. (Credit for this blog goes to all developer who mentioned these answers on multiple blogs, QnA sites and Apple Developer documentation)
1.Explain what is protocol in Objective-C.
A protocol declares a programmatic interface that any class may choose to implement. Protocols make it possible for two classes distantly related by inheritance to communicate with each other to accomplish a certain goal.
Read more here.
2. Explain types of protocol.
A formal protocol declares a list of methods that client classes are expected to implement. Formal protocols have their own declaration, adoption, and type-checking syntax. You can designate methods whose implementation is required or optional with the @required and @optional keywords. Subclasses inherit formal protocols adopted by their ancestors. A formal protocol can also adopt other protocols. Formal protocols are an extension to the Objective-C language.
An informal protocol is a category on NSObject, which implicitly makes almost all objects adopters of the protocol. (A category is a language feature that enables you to add methods to a class without subclassing it.) Implementation of the methods in an informal protocol is optional. Before invoking a method, the calling object checks to see whether the target object implements it. Until optional protocol methods were introduced in Objective-C 2.0, informal protocols were essential to the way Foundation and AppKit classes implemented delegation.
3. Explain what is #import.
#import ensures that a file is only ever included once so that you never have a problem with recursive includes.
4. What is the difference between #import and #include in Objective-C?
import is super set of include, it make sure file is included only once. this save you from recursive inclusion. about “” and <>. “” search in local directory and <> is use for system files.
5.What is the use of category in Objective-C?
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.
#import “SystemClass.h”
@interface SystemClass (CategoryName)
// method declarations
@end
6. Limitations and problems with category?
Advantages: You can extend any class, even those, for which you do not have the source. Look, for example, into the UI extensions added by Apple to the NSString class for rendering, getting the metrics, etc. Since you have access to all instance variables, categories provide you with a nice way to structure your code across compilation units using logical grouping instead of the “it must all be in one phyiscal place” approach taken, for example, by Java. Disadvantages: You cannot safely override methods already defined by the class itself or another category.
7.Explain when to use NSArray and NSMutableArray. Which one is faster and threadsafe?
NSArray and its subclass NSMutableArray manage ordered collections of objects called arrays. NSArray creates static arrays, and NSMutableArray creates dynamic arrays
Read more here.
8. What is fast enumeration?
The object is usually a collection such as an array or set Several Cocoa classes, including the collection classes, adopt the NSFastEnumeration protocol. You use it to retrieve elements held by an instance using a syntax similar to that of a standard C for loop, as illustrated in the following example:
NSArray *anArray = // get an array;
for (id element in anArray)
{
/* code that acts on the element */
}
read more here.
9.Explain what is @synthesize in Objective-C
@synthesize creates a getter and a setter for the variable. This lets you specify some attributes for your variables and when you @synthesize that property to the variable you generate the getter and setter for the variable.
10.Explain how to call function in Objective-C.
calling the method is like this
[className methodName]
however if you want to call the method in the same class you can use self
[self methodName]
11. Explain what is dot notation
The dot syntax is just a shortcut for calling getters and setters, that is:
[foo length]
foo.length
are exactly the same, as are:
[foo setLength:5]
foo.length = 5
12.Mention whether NSObject is a parent class or derived class.
Objective-C defines a root class from which the vast majority of other classes inherit, called NSObject. When one object encounters another object, it expects to be able to interact using at least the basic behavior defined by the NSObject class description.
read more here.
13.Explain the difference between atomic and nonatomic synthesized properties.
Atomic is the default behavior will ensure the present process is completed by the CPU, before another process accesses the variable is not fast, as it ensures the process is completed entirely
Non-Atomic is NOT the default behavior faster (for synthesized code, that is, for variables created using @property and @synthesize) not thread-safe may result in unexpected behavior, when two different process access the same variable at the same time.
14. What is GCD? What are advantages over NSThread?
GrandcentralDispatch: Because your device only has one processor, GCD probably only creates one thread for executing blocks and your blocks execute sequentially. You’ve created 10 different threads, though, and those each get a little piece of the available processing time. Fortunately, sleeping isn’t very processor-intensive, so all your threads run together pretty well. Try a similar test on a machine with 4 or 8 processing cores, and you’ll see GCD run more of your blocks in parallel.
The nice thing about GCD isn’t that it necessarily offers better performance than threads, it’s that the programmer doesn’t have to think about creating threads or matching the number of threads to the number of available processors. You can create lots of little tasks that will execute as a processor becomes available and let the system schedule those tasks for you.
15. What is KVC and KVO? Give an example of using KVC to set value.
Key-Value-Coding (KVC) means accessing a property or value using a string. id someValue = [myObject valueForKeyPath:@”foo.bar.baz”];
Which could be the same as:
id someValue = [[[myObject foo] bar] baz];
Key-Value-Observing (KVO) allows you to observe changes to a property or value.
To observe a property using KVO you would identify to property with a string; i.e., using KVC. Therefore, the observable object must be KVC compliant.
[myObject addObserver:self forKeyPath:@”foo.bar.baz” options:0 context:NULL];
16. What are blocks and how are they used?
Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values.
The syntax to define a block literal uses the caret symbol (^), like this:
^{
NSLog(@”This is a block”);
}
17. What is responder chain?
The responder chain is a series of linked responder objects. It starts with the first responder and end with the app object. If the first responder cannot handle an event, it forwards the event to the next responder in the responder chain.
18. What is id?
id is a pointer to any type, but unlike void * it always points to an Objective-C object. For example, you can add anything of type id to an NSArray, but those objects must respond to retain and release .
19. What is instanceType?
@interface A :
NSObject — (instancetype)init;
@end
@interface B : A
@end
The init method from A is inherited to B. However, in both classes the method has a different return type. In A the return type is A and in B the return type is B.
There is no other way to declare the return type for initializers correctly. Note that most programming languages with classes don’t even have return types for constructors, therefore they completely avoid the issue.
This is the reason why Obj-C needs instancetype but of course it can be used outside initializers, too.
20. Are id and instanceType same? If not, what are differences between them?
In your code, replace occurrences of id as a return value with instancetype where appropriate. This is typically the case for init methods and class factory methods. Even though the compiler automatically converts methods that begin with “alloc,” “init,” or “new” and have a return type of id to return instancetype, it doesn’t convert other methods. Objective-C convention is to write instancetype explicitly for all methods.
21. Does Objective-C have function overloading?
objective-C does not support method overloading, so you have to use different method names.
22. What is delegate? Can delegates be retained?
A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program.
It’s up to you. If you declare it to be retained (strong in ARC) it’ll be retained.
The rule is to not retain it because it’s already retained elsewhere and more important you’ll avoid retain cycles.
23. What is class extension? Why do we require them?
Objective-C allows you to add your own methods to existing classes through categories and class extensions.
Class Extensions Extend the Internal Implementation.
A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension). The methods declared by a class extension are implemented in the @implementation block for the original class so you can’t, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString.
The syntax to declare a class extension is similar to the syntax for a category, and looks like this:
@interface ClassName ()
@end
Because no name is given in the parentheses, class extensions are often referred to as anonymous categories. Unlike regular categories, a class extension can add its own properties and instance variables to a class.
read more here.
24. Who calls dealloc method? Can we implement dealloc in ARC? If yes, what is the need to do that?
dealloc is called as a result of memory management. Once an objects “retainCount” reaches 0 then a dealloc message is automatically sent to that object.
You should never call dealloc on objects unless it is a call to [super dealloc]; at the end of an overridden dealloc.
(void)dealloc
{
[ivar release]; //Release any retained variables before super dealloc
[super dealloc]; //Only place in your code you should ever call dealloc
}
25. Can you write setter method for a retain property?
Yes, To provide custom access logic, you will need to write your own getter and setter methods.
26. How does dispatch_once manages to run only once?
dispatch_once() is synchronous process and all GCD methods do things asynchronously (case in point, dispatch_sync() is synchronous)
The entire idea of dispatch_once() is “perform something once and only once”, which is precisely what we’re doing. dispatch_once that’s used to guarantee that something happens exactly once, no matter how violent the program’s threading becomes.
27. What are NSAutoreleasePool? When to use them?
The NSAutoreleasePool class is used to support Cocoa’s reference-counted memory management system. An autorelease pool stores objects that are sent a release message when the pool itself is drained.
Also, If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks. For example, in place of:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Code benefitting from a local autorelease pool.
[pool release];
You would write:
@autoreleasepool
{
// Code benefitting from a local autorelease pool.
}
@autoreleasepool blocks are more efficient than using an instance of NSAutoreleasePool directly; you can also use them even if you do not use ARC.
28.Does a thread created using performSelectorInBackground:withObject: creates its own autorelease pool?
The performSelectorInBackground:withObject: method creates a new detached thread and uses the specified method as the entry point for the new thread. For example, if you have some object (represented by the variable myObj) and that object has a method called doSomething that you want to run in a background thread, you could could use the following code to do that:
[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];
The effect of calling this method is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object, selector, and parameter object as parameters. The new thread is spawned immediately using the default configuration and begins running. Inside the selector, you must configure the thread just as you would any thread. For example, you would need to set up an autorelease pool (if you were not using garbage collection) and configure the thread’s run loop if you planned to use it. For information on how to configure new threads, see “Configuring Thread Attributes.”
You must read this before going to face interview.
29. Is Objective C, a dynamic language? True/False, explain.
True, Objective-C (don’t forget the hyphen) is a cross between C and Smalltalk. The former is a statically typed language. The latter is dynamically typed. So Objective-C is not only a dynamic language.
30. What happens when we invoke a method on a nil pointer?
A message sent to a nil object is perfectly acceptable in Objective-C, it’s treated as a no-op. There is no way to flag it as an error because it’s not an error, in fact it can be a very useful feature of the language. It returns 0, nil, a structure filled with 0s, etc.
31. When might you use a CFArray/Dictionary instead of a NSArray/Dictionary?
Core Foundation is the brains of the operation. It’s written mostly in C. It was created with Apple’s acquisition of NEXT and their APIs and owes a lot to them. The NS* classes are often just Objective C abstract interfaces built on top of the CF* types. So, when you ask why both CFArray and NSArray exist, the answer is that they actually don’t. NSArrays are CFArrays, NSStrings are CFStrings, etc. That’s why toll-free-bridging is possible.
32. What is toll-free bridging and when is it useful?
Toll-free bridging means that the data structures are interchangeable. It is just as simple as casting — that’s the “toll-free” part. Anyplace you can use the type on one side of the bridge, you can use the other. So, for example, you can create a CFString and then send NSString messages to it, or you can create an NSArray and pass the array to CFArray functions.
33. What does @synchronized() do?
The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do — it prevents different threads from acquiring the same lock at the same time.
34.What is the difference between underscore and self (i.e self.xx and _xx) ?
when you are using the self.XX, you access the property via the setter or getter.
when you are using the _XX, you access the property directly skip the setter or getter
35. What is an extension?
Extensions are actually categories without the category name. It’s often referred as anonymous categories. The syntax to declare a extension uses the @interface keyword, just like a standard Objective-C class description, but does not indicate any inheritance from a subclass. Instead, it just adds parentheses, as shown below
@interface ClassName ()
@end
36. What is a process, thread?
Both processes and threads are independent sequences of execution. The typical difference is that threads (of the same process) run in a shared memory space, while processes run in separate memory spaces.
37.Reflection? Class Introspection? is there anything in objc and cocoa?
Class Introspection: It is the ability to provide information about objects/classes at runtime . Objective C runtime supports introspection. A small sample of the type of information provided by the objC runtime
- names of methods of class from a class object.
2) information about method arguments
3) implementation(IMP) of individual methods of a class
4) Information about instance variables of a class
Reflection: Its the ability to add new classes and to add/modify interfaces of existing classes. It also includes the ability to modify the relationship between classes For example, the objC runtime allows new classes to be added, methods to be added to a class and instance variables to be added to a class created at runtime. It also allows the superclass of a class to be replaced by another class.
Swizzling: The term “Swizzling” in objective C refers to exchanging the implementation of two methods(class or instance) at runtime. So you apply introspection to access method implementations and reflection to actually exchange the method implementation to achieve swizzling.
read more here.
38. How to make a code snippet thread safe?
Thread-safe code is code that remains correct when executed by multiple threads. Thus, No sequence of operations can violate the specification.
1 Invariants and conditions will hold during multithread execution without requiring additional synchronization by the client
2. The high level takeaway point is: thread-safe requires that the specification holds true during multithread execution. To actually code this, we have to do just one thing: regulate the access to mutable shared state
3. And there are three ways to do it: Prevent the access. Make the state immutable. Synchronize the access.
The first two are simple. The third one requires preventing the following thread-safety problems:
liveness deadlock: two threads block permanently waiting for each other to release a needed resource.
livelock: a thread is busy working but it’s unable to make any progress.
starvation: a thread is perpetually denied access to resources it needs in order to make progress.
safe publication: both the reference and the state of the published object must be made visible to other threads at the same time.
race conditions: A race condition is a defect where the output is dependent on the timing of uncontrollable events. In other words, a race condition happens when getting the right answer relies on lucky timing. Any compound operation can suffer a race condition, example: “check-then-act”, “put-if-absent”. An example problem would be if (counter) counter — ;, and one of several solutions would be
@synchronize(self)
{
if (counter) counter — ;
}.
39.What happens when you create a block?
Blocks are also used for callbacks, defining the code to be executed when a task completes. As an example, your app might need to respond to a user action by creating an object that performs a complicated task, such as requesting information from a web service. Because the task might take a long time, you should display some kind of progress indicator while the task is occurring, then hide that indicator once the task is complete.
40. What is the isa member?
Objective-C objects are basically C structs. Each one contains a field called isa, which is a pointer to the class that the object is an instance of (that’s how the object and Objective-C runtime knows what kind of object it is).
41. What happens if you add your just created object to a mutable array, and you release your object?
It depends. If you owned the object before adding it to the array, you still must release your own ownership claim to avoid a leak — the array’s ownership claim on the object is separate, and does nothing to absolve you of your own responsibility with respect to the memory management rules.
Object *obj = [[Object alloc] init];
[anArray addObject:obj];
[obj release];
On the other hand, if you did not own the object, then you still don’t own it after you add it to the array, and still must not release it. The array does establish its own ownership claim, but just like your own code, it’s responsible for balancing its own claims.
Object *obj = [Object object];
[anArray addObject:obj];
// or, avoiding a temp variable
[anArray addObject:[Object object]];
42. What happens with the objects if the array is released?
Releasing the array has the same effect as removing all the items from the array. That is, the array no longer claims ownership of them. If anyone else has retained the objects, they’ll continue to exist. If not, they’ll be deallocated.
43. What can’t we put into an array or dictionary?
nil is not an object that you can add to an array: An array cannot contain nil. This is why addObject:nil crashes.
44. How can we put nil it into dictionary/array?
The nil in initWithObjects: is only there to tell the method where the list ends, because of how C var args work. When you add objects one-by-one with addObject: you don’t need to add a nil.
45. What is posing in Objective C?
Posing. Objective-C permits a class to entirely replace another class within an application. The replacing class is said to “pose as” the target class. All messages sent to the target class are then instead received by the posing class.
46. Can we create Dynamic Classes in Objective C? If Yes, Explain how to create with a valid use case?
For instantiating a class using its name, you can use
NSClassFromString: id obj = [[NSClassFromString(@”MySpecialClass”) alloc] init];
47. What happen if we send any message to an object which is released?
Calling release on an object does not necessarily mean it’s going to be freed. It just decrements the object’s retain count. It’s not until the retain count reaches 0 the object gets freed (and even then, the object might be in an autorelease pool and still not be freed quite then).
So, you might release your object but you could still be pointing to it. And then it could get autoreleased. And then you send it a message — but maybe the object is garbage now.
48. What are the CPU architectures supported by iOS devices?
Armv7s supported from iPhone 5, 5c, 5S, iPod touch-5, iPad-4, iPad Air. that’s nothing but based on processor. Armv7s designed for A6 processor. Supporting from IOS6+. It’s also support for 64-bit coding but processing get slow in those devices with armv7s instruction set.
Same as, Arm64 devices are from Iphone 5s, iPad Air. That’s related to A7 Processor. Best advantage of these device is 64-bit support.
49. Can I write some C++ function in same .m file? Will it compile? If no, what changes should I do to compile it?
The easiest solution is to simply tell Xcode to compile everything as Objective C++.
Set your project or target settings for Compile Sources As to Objective C++ and recompile.
Then you can use C++ or Objective C everywhere.
50. What are the types of iOS binaries you can create using XCode? (.app, .ipa, .a, .framework)
you can create .app,.ipa,.a and .framework
51. Can a static library (.a) contain resources like images, sound files etc?
NO, You can’t provide anything other than code with a static library. This is because .a files are a simple archive of object files, with the added ability under Mac/iOS of supporting multiple CPU architectures.
The only option you have is to create a Framework, which can provide code as well as other resources.
52. What is bundle?
A bundle is simply a self contained executable file. When you run it, it executes a main function that is defined inside, and uses only the resources that it contains.
53. Explain application life cycle or application states.
These states are known as states of the app’s lifecycle. As an app moves through the states of its lifecycle, the state of the app is defined by its level of activity such as Not Running, Active or Suspended.
Here’s more information about the states:
-When an app is in the Not Running state, either the app hasn’t been launched or the system shut it down.
-When an app starts, it transitions through a short state, called the Inactive state. It’s actually running, but it’s performing other functions and isn’t ready to accept user input or events.
-An app in an Active state is running in the foreground and receiving events. This is the normal mode for foreground apps — apps that don’t have to run in the background without a user interface.
-When an app is in the Background state, its user interface isn’t visible, but it is running. Most apps transition through this state on their way to being suspended.
-An app may need (and request) extra execution time and may stay in this state for a time. In addition, certain apps run in the background. Such an app enters the Background state directly and doesn’t go through the Inactive state.
-The iOS system may move an app to a Suspended state. Here the app is in the background but is not running code. It does stay in memory, though. If a low-memory condition occurs, the system may purge apps in the suspended state without notice. Note that, according to Apple’s standards, only the iOS system can kill an app.
54. Why create a custom view?
You can also create a custom view to to encapsulate the visual appearance and behavior of your own reusable component. For example, in a news reading application we might want a standard component to display images with a caption using a consistent style on both the home page view controller as well as the individual story view controller.
55. What are the size classes?
Size classes are traits assigned to user interface elements, like scenes or views. They provide a rough indication of the element’s size.
56. How we can layout subviews in a view?
addSubview causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target.
57. Difference between UIWindow and UIView.
Windows do not have any visible content themselves but provide a basic container for your application’s views. Views define a portion of a window that you want to fill with some content. Typically, there is only one window in an iOS application.
58. Can we have multiple UIWindows in iOS?
Yes, apps may have an additional window for content displayed on an external display.
59. What are benefits of collections views?
- Allows customizable layout that can be very complex(example: different sizing of each cell)
- Supports multiple cells in one row
- Provides horizontal scroll direction, eliminates the need to create scroll view to achieve the same effect
- Supports custom animations for cells based on layout
- Can implement drag and drop functionality
- More options for headers and footers settings, it does not need to be anchored on the top or bottom
- Does not include blank cells
60. Difference in Xib/storyboard vs nib?
There are things you can do with a storyboard that you can’t do with a nib. A storyboard lets you create segues between view controllers, and it lets you design table view cells in-place.
There are things you can do with a nib that you can’t do with a storyboard. In a nib, you can create references to the File’s Owner placeholder. You can create multiple top-level views, edit them, and create connections between them. See this answer for an example of why you’d want to do that. You can add external object placeholders (a rarely-used feature).
Check part 2 here.