iOS Interview Questions Compilation

Bored 🥑
13 min readAug 2, 2017

--

This article is outdated. Please checkout my latest articles in iOS Interview Preparation Complete Guide.

iOS Interview Prep Series

iOS Interview Prep 0 — Intro
iOS Interview Prep 1 — Memory management
iOS Interview Prep 2 — Autorelease Pool
iOS Interview Prep 3 — Blocks and Closures
iOS Interview Prep 4 — Event Handling & Responder Chain
iOS Interview Prep 5 — Singletons
iOS Interview Prep 6 — Dependency Injection
iOS Interview Prep 7 — Concurrency Part 1
iOS Interview Prep 7 — Concurrency Part 2
iOS Interview Prep 8 — View and Layout
iOS Interview Prep 9 — App performance
iOS Interview Prep — Testing Strategy
iOS Interview Prep 10 — Unit Test
iOS Interview Prep 11 — Integration Test
iOS Interview Prep 12 — Snapshot Test

General

  1. Explain frame and bounds, center and their relationship?
  2. What is Responder Chain ?
  3. Explain View Controller Lifecycle events order ?
  4. What are the states of an iOS App?
  5. What are the most important application delegate methods a developer should handle ?
  6. What’s your preference when writing UI’s? Xib files, Storyboards or programmatic UIView?
  7. What is the resueIdentifier in table view used for?
  8. What considerations do you need when writing a UITableViewController which shows images downloaded from a remote server?
  9. What is AutoLayout? What does it mean when a constraint is “broken” by iOS?

Memory Management

  1. Why don’t we use strong for enum property in Objective-C ?
  2. What is the difference strong, weaks, read only and copy ?
  3. How many different nullability annotations available in Objective-C ?
  4. Explain [weak self] and [unowned self] ?
  5. What is ARC ?
  6. What is the difference between property and instance variable?

Objective-C Runtime

  1. What is Dynamic Dispatch ?
  2. What is synthesize in Objective-C ?
  3. What is dynamic in Objective-C ?
  4. Explain Selectors in Objective-C ?
  5. What is method swizzling in Objective C and why would you use it?

Blocks And Closure

  1. What’s the difference between Block and Completion Handler ?
  2. What are blocks and how are they used?

Answers

Question 1

Blocks are a language-level feature added to Objective-C, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary. They can be executed in a later time, and not when the code of the scope they have been implemented is being executed. Their usage leads eventually to a much cleaner and tidier code writing, as they can be used instead of delegate methods, written just in one place and not spread to many files.

Whereas completion handler is a way (technique) for implementing callback functionality using blocks. A completion handler is nothing more than a simple block declaration passed as a parameter to a method that needs to make a callback at a later time. Completion handler should always be the last parameter in a method. A method can have as many arguments as you want, but always have the completion handler as the last argument in the parameters list.

Concurrency and Multi-threading

  1. What’s the difference between asynchronous and synchronous task?
  2. What is Concurrency ?
  3. Explain how Grand Central Dispatch (GCD) works?
  4. What is Readers-Writers?
  5. Explain NSOperation — NSOperationQueue — NSBlockOperation
  6. Explain Priority Inversion and Priority Inheritance.
  7. Explain the difference between atomic and nonatomic synthesized properties
  8. What mechanisms does iOS provide to support multi-threading?
  9. What’s the difference between dispatch_once and synchronized?
  10. How to create a singleton ?

Answers

Question 1

A Synchronous function returns control to the caller after the task is completed.

An asynchronous function returns immediately, ordering the task to be done but not waiting for it. Thus, an asynchronous function does not block the current thread of execution from proceeding on to the next function.

Question 2

Concurrency is the notion of multiple tasks running at the same time. Single-core devices can achieve concurrency through time-slicing. They would run one thread, perform a context switch, then run another thread. Multi-core devices on the other hand, execute multiple threads at the same time via parallelism. Basically, concurrency is about structure and parallelism is about execution.

Question 3

GCD is built on top of threads. Under the hood it manages a shared thread pool. With GCD you add blocks of code or work items to dispatch queues and GCD decides which thread to execute them on. Note that GCD decides how much parallelism is required based on the system and available system resources. It offers the following benefits:

  1. GCD can improve your app’s responsiveness by helping you defer computationally expensive tasks and run them in the background.
  2. GCD provides an easier concurrency model than locks and threads and helps to avoid concurrency bugs.
  3. GCD can potentially optimize your code with higher performance primitives for common patterns such as singletons.

Question 4

Some threads may read and some may write, with the constraint that no process may access the shared resource for either reading or writing while another process is in the act of writing to it. It’s not safe to let one thread modify the array while another is reading it. GCD provides an elegant solution of creating a Readers-writer lock using dispatch barriers.

An RW lock allows concurrent access for read-only operations, while write operations require exclusive access. This means that multiple threads can read the data in parallel but an exclusive lock is needed for writing or modifying data. When a writer is writing the data, all other writers or readers will be blocked until the writer is finished writing.

Dispatch barriers are a group of functions acting as a serial-style bottleneck when working with concurrent queues. Using GCD’s barrier API ensures that the submitted block is the only item executed on the specified queue for that particular time. This means that all items submitted to the queue prior to the dispatch barrier must complete before the block will execute.

When the block’s turn arrives, the barrier executes the block and ensures that the queue does not execute any other blocks during that time. Once finished, the queue returns to its default implementation. GCD provides both synchronous and asynchronous barrier functions.

Question 5

NSOperation adds a little extra overhead compared to GCD, but we can add dependency among various operations and re-use, cancel or suspend them.

NSOperationQueue, It allows a pool of threads to be created and used to execute NSOperations in parallel. Operation queues aren’t part of GCD.

NSBlockOperation allows you to create an NSOperation from one or more closures. NSBlockOperations can have multiple blocks, that run concurrently.

Question 6

Priority inversion describes a condition where a low priority task blocks a high priority task from executing. effectively inverting task priorities.

In general, don’t use different priorities. Often you will end up with high-priority code waiting on low-priority code to finish. When you’re using GCD, always use the default priority queue (directly, or as a target queue). If you’re using different priorities, more likely than not, it’s actually going to make things worse.

One of the solution for this problem is Priority Inheritance. In Priority Inheritance, when L is in critical section, L inherits priority of H at the time when H starts pending for critical section. By doing so, M doesn’t interrupt L and H doesn’t wait for M to finish. Please note that inheriting of priority is done temporarily.

Question 7

Atomic and non-atomic refers to whether the setters/getters for a property will atomically read and write values to the property. When the atomic keyword is used on a property, any access to it will be “synchronized”. Therefore a call to the getter will be guaranteed to return a valid value, however this does come with a small performance penalty.

Using atomic properties alone won’t make your classes thread-safe. It will only protect you against race conditions in the setter, but won’t protect your application logic. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned — the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.

Question 8

Threads, Grand Central Dispatch, NSOperation

Question 9

dispatch_once executes a block object once and only once for the lifetime of an application.
If called simultaneously from multiple threads, this function waits synchronously until the block has completed.

Synchronized declares a critical section around the code block. In multithreaded code, @synchronized guarantees that only one thread can be executing that code in the block at any given time.

Question 10

Architecture and Design Pattern

  1. Why is design pattern very important ?
  2. Explain MVC and MVVM
  3. What is Singleton Pattern ?
  4. What is Facade Design Pattern ?
  5. What is Decorator Design Pattern ?
  6. What is Adapter Pattern ?
  7. What is Observer Pattern ?
  8. KVC — KVO
  9. What problems does delegation solve?
  10. What is the difference between a delegate and an NSNotification?
  11. Where do we use Dependency Injection ?
  12. When is a good time for dependency injection in our projects?
  13. What is the difference Delegates and Callbacks ?
  14. What are some pitfalls you’ve experienced with it? Are there any alternatives to MVC?

Networking

  1. What is Alamofire doing?
  2. REST, HTTP, JSON — What’s that?
  3. What kind of JSONSerialization have ReadingOptions ?
  4. Please explain SOAP and REST Basics differences ?
  5. What’s the difference between default, ephemeral, background session?
  6. What makes a good image cache?

Answers

Question 1

Alamofire provides chainable request/response methods, JSON parameter and response serialization, authentication, and many other features. In this Alamofire tutorial, you’ll use Alamofire to perform basic networking tasks like uploading files and requesting data from a third-party RESTful API.
Alamofire’s elegance comes from the fact it was written from the ground up in Swift and does not inherit anything from its Objective-C counterpart, AFNetworking.

Question 2

REST, or REpresentational State Transfer, is a set of rules for designing consistent, easy-to-use and maintainable web APIs. REST has several architecture rules that enforce things such as not persisting states across requests, making requests cacheable, and providing uniform interfaces. This makes it easy for app developers like you to integrate the API into your app — without needing to track the state of data across requests.

JSON stands for JavaScript Object Notation; it provides a straightforward, human-readable and portable mechanism for transporting data between two systems. JSON has a limited number of data types: string, boolean, array, object/dictionary, null and number; there’s no distinction between integers and decimals. Apple supplies the JSONSerialization class to help convert your objects in memory to JSON and vice-versa.

Question 3

Question 5

Default session behaves similarly to other Foundation methods fro downloading URLs. They use a persistent disk-based cache and store credentials in the user’s keychain.

Ephemeral sessions do not store any data to disk; all caches, credential stores, and so on are kept in RAM and tied to the session. Thus, when your app invalidates the session, they are purged automatically.

Background sessions are similar to default sessions, except that a separate process handles all data transfers.
Background session is similar to Default session, But it can be used to perform networking operations on behalf of a suspended application, within certain constraints.

Question 6

A strong iOS image cache component must:

  • download images asynchronously, so the main queue is used as little as possible
  • decompress images on a background queue. This is far from being trivial. See a strong article about background decompression
  • cache images into memory and on disk. Caching on disk is important because the app might be closed or need to purge the memory because of low memory conditions. In this case, re-loading the images from disk is a lot faster than downloading them. Note: if you use NSCache for the memory cache, this class will purge all it’s contents when a memory warning is issued.
  • store the decompressed image on disk and in memory to avoid redoing the decompression
  • use GCD and blocks. This makes the code more performant, easier to read and write. In nowadays, GCD and blocks is a must for async operations
  • nice to have: category over UIImageView for trivial integration. nice to have: ability to process the image after download and before storing it into the cache.

Error Handling

  1. What is NSError object made of ?
  2. What are benefits of Guard ?
  3. Explain throw

Unit Testing

  1. What’s Code Coverage ?
  2. What is the Test Driven Development of three simple rules ?
  3. What is difference between BDD and TDD ?
  4. Please explain “Arrange-Act-Assert”
  5. What is the benefit writing tests in iOS apps ?
  6. What is Continuous Integration ?
  7. What is the disadvantage to hard-coding log statements ?

Data Storage

  1. What is Realm benefits ?
  2. What is CoreData ?

Notification

  1. Please explain types of notifications.
  2. Explain how to impelement remote notification?

Objective-C

  1. What is instancetype in Objective-C?
  2. Explain static variable in Objective-C?
  3. How do you create and store your constants?
  4. Objective-C what is associated object?
  5. What is a category and when is it used?

Swift

  1. What is the Swift main advantage ?
  2. Explain generics in Swift ?
  3. Explain lazy in Swift ?
  4. Explain what is defer ?
  5. How to pass a variable as a reference ?
  6. Please explain Swift’s pattern matching techniques
  7. Please explain Method Swizzling in Swift
  8. What is the difference Non-Escaping and Escaping Closures ?
  9. Please explain final keyword into the class ?
  10. What is the difference open & public access level ?
  11. What is the difference fileprivate &private access level ?
  12. Explain If let structure
  13. Explain Swift Standart Library Protocol
  14. What is Downcasting ?
  15. Why is everything in a do-catch block?
  16. Explain subscripts ?
  17. What is DispatchGroup ?
  18. What is the difference ANY and ANYOBJECT ?
  19. Could you explain Associatedtype ?
  20. What is Hashable ?
  21. When do you use optional chaining vs. if let or guard ?
  22. How many different ways to pass data in Swift ?
  23. How do you follow up clean code for this project ?
  24. Explain to using Class and Inheritance benefits
  25. What’s the difference optional between nil and .None?
  26. What is GraphQL ?
  27. Explain Common features of Protocols & superclasses

Git

  1. Which git command saves your code without making a commit ?
  2. Which git command allows us to find bad commits ?
  3. What allows you to combine your commits ?

Security

  1. How would you securely store private user data offline on a device? What other security best practices should be taken?

Again there is no right answer to this, but it’s a great way to see how much a person has dug into iOS security. If you’re interviewing with a bank I’d almost definitely expect someone to know something about it, but all companies need to take security seriously, so here’s the ideal list of topics I’d expect to hear in an answer:

  • If the data is extremely sensitive then it should never be stored offline on the device because all devices are crackable.
  • The keychain is one option for storing data securely. However it’s encryption is based on the pin code of the device. User’s are not forced to set a pin, so in some situations the data may not even be encrypted. In addition the users pin code may be easily hacked.
  • A better solution is to use something like SQLCipher which is a fully encrypted SQLite database. The encryption key can be enforced by the application and separate from the user’s pin code.

Other security best practices are:

  • Only communicate with remote servers over SSL/HTTPS.
  • If possible implement certificate pinning in the application to prevent man-in-the-middle attacks on public WiFi.
  • Clear sensitive data out of memory by overwriting it.
  • Ensure all validation of data being submitted is also run on the server side.

Others

  1. How to Prioritize Usability in Design ?
  2. What is Regular expressions ?
  3. What is Operator Overloading ?
  4. What is Downcasting ?
  5. Implement an array enumeration block
  6. What is bitcode
  7. What is the difference SVN and Git
  8. What is the difference between LLVM and Clang?
  9. When and why do we use an object as opposed to a struct?
  10. What does code signing do?
  11. Explain difference between SDK and Framework ?
  12. What is RGR ( Red — Green — Refactor ) ?
  13. What is Keychain ?
  14. Why do we use availability attributes ?
  15. How could we get device token ?
  16. A product manager in your company reports that the application is crashing. What do you do?

What is the difference between viewDidLoad and viewDidAppear?
Which should you use to load data from a remote server to display in the view?

viewDidLoad is called when the view is loaded, whether from a Xib file, storyboard or programmatically created in loadView. viewDidAppear is called every time the view is presented on the device. Which to use depends on the use case for your data. If the data is fairly static and not likely to change then it can be loaded in viewDidLoad and cached. However if the data changes regularly then using viewDidAppear to load it is better. In both situations, the data should be loaded asynchronously on a background thread to avoid blocking the UI.

What is a protocol, and how do you define your own and when is it used?

A protocol is similar to an interface from Java. It defines a list of required and optional methods that a class must/can implement if it adopts the protocol. Any class can implement a protocol and other classes can then send messages to that class based on the protocol methods without it knowing the type of the class.

What is KVC and KVO? Give an example of using KVC to set a value.

KVC stands for 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 stands for Key-Value Observing and allows a controller or class to observe changes to a property value.

Let’s say there is a property name on a class:

@property (nonatomic, copy) NSString *name;

We can access it using KVC:

NSString *n = [object valueForKey:@"name"]

And we can modify it’s value by sending it the message:

[object setValue:@"Mary" forKey:@"name"]

A product manager in your company reports that the application is crashing. What do you do?

This is a great question in any programming language and is really designed to see how you problem solve. You’re not given much information, but some interviews will slip you more details of the issue as you go along. Start simple:

  • get the exact steps to reproduce it.
  • find out the device, iOS version.
  • do they have the latest version?
  • get device logs if possible.

Once you can reproduce it or have more information then start using tooling. Let’s say it crashes because of a memory leak, I’d expect to see someone suggest using Instruments leak tool. A really impressive candidate would start talking about writing a unit test that reproduces the issue and debugging through it.

Other variations of this question include slow UI or the application freezing. Again the idea is to see how you problem solve, what tools do you know about that would help and do you know how to use them correctly.

--

--