iOS Interview Questions Part 1: Differentiate đźŽ
--
iOS Domain is pretty enormous and deep. If you are looking for iOS Development interview questions for the beginner or experienced, then this is the right place. I have prepared some questions and bifurcated in various parts, combining in one story won’t justify this topic.
In this part, we will be differentiating between many known terms in iOS. We come across many terms which seems or sounds similar but are slightly different or completely different. This part will mostly focus on iOS Core development and Objective-C. Swift specific terms will be discussed in separate Part. :)
Q: @synthesis VS @dynamic
@ synthesize will generate getter and setter methods for your property at compile time.
@ dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass or will be provided at runtime).
Uses for @dynamic are 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.
Q: XIB VS NIB
XIB(XML Interface Builder) is executable code in Xcode. It is comparatively bigger in size than nib. These are flat and XML files
NIB(Nxt Interface Builder) is a non-editable and inoperable file. They are smaller in size. These are binary or archive files. After compilation XIB converts into NIB.
Q: NSInteger VS Int VS NSNumber
NSInteger is a type definition that describes an integer — but it is NOT equivalent to int
on 64-bit platforms. It is defined as int
when building a 32-bit app and as long
for 64-bit apps. Most of the time you can replace int with NSInteger, but there are some things to consider when doing so.
Int is a primitive data type.
NSNumber stores numeric type as objects and can convert into a different format. It can also retrive a string representation also.
Q: Any VS Anyobject
According to Apple’s Swift documentation:
- Any can represent an instance of any type at all, including function types and optional types.
- AnyObject can represent an instance of any class type.
Check out for more details.
Q: Category VS Protocol
Protocol declare a set of methods that a class must implement. Methods can be marked as optional or required for the implementing class by @optional and @ required keyword.
Category adds methods to an existing class e.g. NSObject, without modifying the class itself.
Q: Category VS Inheritance
Categories allow expanding the API of existing classes without changing their type. It uses to add new methods, not properties.
Inheritance also expands the API but introduces a new type. Additionally, subclassing lets you add state and add properties as well
Note: We can add properties in categories through Associated Objects. Check this article by Matt Thompson.
Q: Category VS Extension
Note: Extensions in swift are similar to categories in Objective-C. Unlike Objective-C categories, Swift extensions do not have names.
Extensions (Swift)add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code.
Categories(Objc-C only) allow you to add methods outside of the main interface file. Whereas Extensions(Objc-C) must be implemented in the main Interface file. Which means we cannot use extensions for extending Builtin classes or Classes for which you don’t have the source code, there you should use Categories.
Q: NSSet VS NSArray
NSSet primarily accesses item by comparison. They are unordered, no duplication is allowed.
NSArray access item by index. They allow duplicate item and are ordered.
Q: NSDictionary VS NSMutableArray
NSDictionary is unordered and stores object as a key-value pair. Objects are accessed by addressing them with an arbitrary string value.
NSMutableArray is similar to NSArray except that its content is dynamic i.e. can be changed after creating an object.
Q: Delegate VS Notifications
Delegates create a has-a relationship between two classes. It supports two-way communication i.e. we can return the value and it also has a chance to modify or reject the operations as well. It checks protocol methods implementation at compile time. Only one designated object can listen the message. Similar to the telephonic conversation.
Notification based on one to many communication. It cannot receive feedback and have no link between the objects to communicate back and forth. There is no compile time checking for method implementation. Any number of the object can receive the message.
Delegation also avoids tight coupling. It modifies behavior and appearance without the need of subclass objects.
Q: Shallow VS Deep Copy
Shallow Copy is also known as address copy, similar to Call by Reference. It copies the structure, not the data/element. Changes made in one object reflects the other one also. In Objective-C, it can be implemented with copy or mutable copy keyword.
Deep Copy is also similar to call by value. It copies actual data and both objects have their own copy i.e they point to a different array. Changes made in one object does not reflect in another one. In Objective-C, it can be implemented by using methods of NSKeyedArchiver/NSKeyedUnarchiver class.
Please check this awesome implementation in Objective-C.
Q: Atomic VS NonAtomic
Atomic is the default behavior for properties. It ensures the present process is completed by the CPU, before another process accesses the variable, hence it is threaded safe. It is not fast, as it ensures the process is completed entirely.
Non-Atomic is not the default behavior. It is faster (for synthesized code, that is, for variables created using @property and @synthesize). It is not thread-safe and may result in unexpected behavior when two different processes access the same variable at the same time.
What is Thread Safety?
A piece of code is called thread-safe if it gives correct results even in a multi-threaded environment i.e. if it is executed simultaneously by multiple threads it would give the correct result. Thread safety means that the code can handle multiple threads.
Q: Weak VS Strong
A STRONG reference means that you want to “own” the object you are referencing with a property or variable. The compiler will take care that any object that you assign to the property will not be destroyed. Only once you set the property to nil
will the object get destroyed (unless one or more other objects also hold a strong reference to it).
In contrast, with a WEAK reference you signify that you don’t want to have control over the object’s lifetime. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil
. The most frequent use cases of weak references in iOS are:
- delegate properties, which are often referenced weakly to avoid retain cycles, and
- subviews/controls of a view controller’s main view because those views are already strongly held by the main view.
Q: Assign VS Weak
- use weak if you only want a pointer to the object without retaining it — useful for avoid retain cycles (ie. delegates) — it will automatically nil out the pointer when the object is released
- use assign for primatives — exactly like weak except it doesn’t nil out the object when released, it potentially leaves dangling pointers, ie. will access garbage value. Assign and unsafe_unretained are identical in usage.
Q: Retain VS Strong (=)
- strong is the same as retain in a property declaration so for ARC projects use strong instead of retain.
- retain is the same as strong.
- apple says if you write retain it will auto converted/work like strong only.
- methods like “alloc” include an implicit “retain”
Q: Retain VS Copy
retain : It is done on the created object, and it just increase the reference count by one.
copy : Makes a copy of an object, and returns it with retain count of 1. If you copy an object, you own the copy. This applies to any method that contains the word copy where “copy” refers to the object being returned.
Q: Bound VS Frame
A view object tracks its size and location using its frame, bounds, and center properties:
The frame property contains the frame rectangle, which specifies the size and location of the view in its superview’s coordinate system.
The bounds property contains the bounds rectangle, which specifies the size of the view (and its content origin) in the view’s own local coordinate system.
The center property contains the known center point of the view in the superview’s coordinate system.
Q: Nil VS nil VS NSNull
Detailed blog by Matt Thompson.
Q: NSNotificationCenter VS local notification VS push notification
UILocalNotification: Instances of UILocalNotification represent notifications that an application can schedule for presentation to its users at specific dates and times. The operating system is responsible for delivering the notification at the proper time. It does not notify your custom class objects. It will appear as an alert if the app is in the background. UILocalNotifications are only displayed automatically if the app is not running. If the app is running and a local notification fires, UIApplicationDelegate’s didReceiveLocalNotification method gets called and the system doesn’t display anything/play a sound. If you want to display the notification, create an UIAlertView yourself in the delegate method.
NSNotificationCenter: It is internal to the running app and doesn’t require a server or anything special setup. There is no need to get Certificates, Identifiers & Profiles in Apple developer member center. It is used to notify the custom class objects. NSNotification is a message that is sent internally between the objects in the app.
Push Notification: We need to get Certificates, Identifiers & Profiles in Apple developer member center. This indeed requires a server and special setup in the provisioning profile or Info.plist. The message is sent from the server and app handles to display it.
Q: Key-Value Observing VS NSNotificationCenter
Key-Value Observing adds observers for keypath and used to observe changes in property for an object.
NSNotificationCenter adds observers for notifications and used when there are multiple objects are to be notified
Q: Delegate vs target/action
Delegates are usually implemented using Protocols instead of selectors. This is a more formal way of communicating across classes and is most useful when there is more than one method that may be needed. It is used to send and receive data between 2 objects. It is used to 2-Way communication by having methods that return values.
Target/Action are generally used to correspond to an “event-like” situation, such as a click, a timer firing, etc. and is more suitable when the communication is limited to control (events, state, etc). It is mostly manifest 1-Way communication
Q: Content Hugging VS Compression Resistance
Intrinsic Content Size — Pretty self-explanatory, but views with variable content are aware of how big their content is and describe their content’s size through this property. Some obvious examples of views that have intrinsic content sizes are UIImageViews, UILabels, UIButtons.
Content Hugging (Content does not want to grow): The higher this priority is, the more a view resists growing larger than its intrinsic content size.
Compression Resistance (Content does not want to shrink): The higher this priority is, the more a view resists shrinking smaller than its intrinsic content size.
Q: GCD VS NSOperation
GCD
is a low-level C-based API.NSOperation
and NSOperationQueue
are Objective-C classes.NSOperationQueue
is objective C wrapper over GCD
. If you are using NSOperation, then you are implicitly using Grand Central Dispatch.
GCD advantage over NSOperation:
i. implementation
For GCD
implementation is very simple, light-weight and have lock free Algo.NSOperationQueue
is complex, heavy-weight and involves a lot of locking
NSOperation advantages over GCD:
i. Control On Operation
you can Pause, Cancel, Resume an NSOperation
ii. Dependencies
you can set up a dependency between two NSOperations
operation will not started until all of its dependencies return true for finished.
iii. State of Operation
can monitor the state of an operation or operation queue. ready ,executing or finished. Can also compute pending operations.
iv. Max Number of Operation
you can specify the maximum number of queued operations that can run simultaneously
v. Observable
The NSOperation and NSOperationQueue classes have a number of properties that can be observed, using KVO (Key Value Observing). This is another important benefit if you want to monitor the state of an operation or operation queue.
When to Go for GCD
or NSOperation
when you want more control over queue (all above mentioned) use NSOperation
and for simple cases where you want less overhead (you just want to do some work "into the background" with very little additional work) use GCD
Q: Static Vs Dynamic typing
Static typing is when your type checking occurs at compile time. You must define a type for your variables inside of your code and any operations you perform on your data would be checked by the compiler.
Dynamic typing is when your type checking occurs at runtime. Instead of errors coming up when you compile your code you will get runtime errors if you try performing operations on incompatible types. However, you will get the benefit of having more versatile functions as they can be written once for multiple data types.
Q: What is an “app ID” and a “bundle ID” ?
A bundle ID precisely identifies a single app. It is used during the development process to provision devices and by the operating system when the app is distributed to customers.
During the development process, you use an app’s bundle ID in many different places to identify the app.
Whereas, An App ID is a two-part string used to identify one or more apps from a single development team.
The Team ID is supplied by Apple and is unique to a specific development team, while the bundle ID search string is supplied by you to match either the bundle ID of a single app or a set of bundle IDs for a group of your apps.
There are two types of App IDs: an explicit App ID, used for a single app, and wildcard App IDs, used for a set of apps.
Q: KVC VS KVO?
KVC (Key-Value Coding)- It’s a mechanism by which an object’s properties can be accessed using string’s at runtime rather than having to statically know the property names at development time.
KVO (Key-Value Observing)- It allows a controller or class to observe changes to a property value. In KVO, an object can ask to be notified of any changes to a specific property, whenever that property changes value, the observer is automatically notified.
Q: BDD VS TDD
The main difference between BDD and TDD is the fact that BDD test cases can be read by non-engineers, which can be very useful in teams.
Test-Driven Development is a test-first software development methodology, which means that it requires writing test code before writing the actual code that will be tested
Behavior-Driven Development is a methodology that was created based on TDD, but evolved into a process that doesn’t concern only programmers and testers, but instead deals with the entire team and all important stakeholders, technical and non-technical. BDD started out of a few simple questions that TDD doesn’t answer well: how much tests should I write? What should I actually test — and what shouldn’t I? Which of the tests I write will be in fact important to the business or to the overall quality of the product, and which are just my over-engineering?
Some argue that BDD is always better than TDD because it has the possibility of eliminating issues that might arise when using TDD, it isn’t guaranteed to. Issues like poor code organization, bad design practices, etc. will still persist. You’ll just have a lower likely hood of writing bad tests and thus have more robust features.
iOS BDD Framework: Quick & Nimble.
Q: SVN VS Git
SVN relies on a centralised system for version management. It’s a central repository where working copies are generated and a network connection is required for access.
Git relies on a distributed system for version management. You will have a local repository on which you can work, with a network connection only required to synchronise.
Q: JSON VS XML
Q: Rest VS Soap
Check this detail comaparision.
Q: Stack VS Heap
Stack are fast access and don’t have to explicitly de-allocate variables. Space is managed efficiently by CPU and memory will not become fragmented. There is limit on stack size (OS-dependent). Usually variables are stored and they cannot be resized.
With Heap, variable can be accessed globally, but have slow access. It has no memory limit. There is no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed. We need to manage memory.
Q: Static VS Dynamic Library
Static Library(.a)
Static libraries allow an application to load code into its address space at compile time.This results in a larger size on disk and slower launch times. Because the library’s code is added directly to the linked target’s binary, it means that to update any code in the library, the linked target would also have to be rebuilt.
Dynamic Library(.dylib)
Dynamic libraries allow an application to load code into its address space when it’s actually needed at run time. Because the code isn’t statically linked into the executable binary, there are some benefits from loading at runtime. Mainly, the libraries can be updated with new features or bug-fixes without having to recompile and relink executable. In addition, being loaded at runtime means that individual code libraries can have their own initializers and clean up after their own tasks before being unloaded from memory
Q: SQLite vs Core data
SQLite: Primary function is storing and fetching data. It operates on data stored on disk. It can stores “dumb” data and can be transactional, thread-safe and multi-use. Perpetually saved to disk (and often crash resilient) and can be slow to create millions of new rows. It offers data constraints like “unique” keys.
Core Data: Primary function is graph management (although reading and writing to disk is an important supporting feature). It operates on objects stored in memory. It works with fully-fledged objects that self-manage a lot of their behavior and can be subclassed and customized for further behaviors. It is also non-transactional, single threaded, single user. It requires a save process and leaves data constraints to the business logic side of the program
Q: CollectionViews VS TableViews
TableViews display a list of items, in a single column, a vertical fashion, and limited to vertical scrolling only.
CollectionViews also display a list of items, however, they can have multiple columns and rows.
Q: LLVM VS Clang
Clang is the front end of LLVM tool chain ( “clang” C Language Family Frontend for LLVM ). Every Compiler has three parts .
1. Front end ( lexical analysis, parsing )
2. Optimizer ( Optimizing abstract syntax tree )
3. Back end ( machine code generation )
Front end ( Clang ) takes the source code and generates abstract syntax tree ( LLVM IR ).
Q: ARC VS AutoRelease
Autorelease is still used in ARC. ARC is used inside the scope whereas autorelease is used outside the scope of the function.
Where to go next — Part 2 ObjectiveC ⏩
Thanks for reading! I hope this would be useful for understand or refresing some of the iOS concept. Please share your feedback, queries regarding any of the topic in comments below. Till then Adios!!! đź’šđź’šđź’šđź’šđź’š