iOS Interview Questions

About Latest trend

Latest version of iOS, Swift, XCode

Answer:  As per today (22-Dec-2020),

Latest version of XCode : 13

Swift : 5.5
iOS : 15
Mac OS : Big Sur 11.6
Xcode : Xcode 13

1. What’s new in Swift 5?

1. isMultiple(of: 2)

var row = 20

if row % 2 == 0{
    print("Even number")

//in swift 5
if row.isMultiple(of: 2) {
    print("Even number")

2. Creation of raw string 

As of Swift 5, it is possible to create raw strings. This makes it possible to express string literals as they are. Raw strings are created using the # before and after the String value.

var myName = #"Hello! My Name is "Sandesh Sardar" "#

2. What is new in iOS version and what’s new in it from previous version 

Answer:  Two big new features for iOS 13 are Dark Mode (previous its with system app but now can integrate with third party apps) and Sign In with Apple (just like facebook and google).

Diffabledatasource – no need to write datasource in tabelview and collectionview

iOS Coding Concepts

1. What is array? How it create and diff operation on it?

Answer : An array is an ordered collection that stores multiple values of the same type. That means that an array of Int can only store Int values. And you can only insert Int values in it.

//how to create
let names = ["Arthur", "Ford", "Trillian", "Zaphod", "Marvin"] 
Empty array -> let score = [Int]()

//how to add element in array
names += ["Heart of Gold"]

//how to remove
names.remove(at: 2)

//how to insert at particular position 
names.insert("Humma Kavula", at: 4)

3. What is Dictionary? How it create and diff operation on it?

Answer : A dictionary is an unordered collection that stores multiple values of the same type. Each value from the dictionary is associated with a unique key. All the keys have the same type.

//how to declare

var dictionary: [String:Int] = [
    "one" : 1,
    "two" : 2,
    "three" : 3

var emptyDictionary: [Int:Int] = [:]

stringsAsInts["zero"] // Optional(0) // getting value

//how to loop
for (key, value) in userInfo {
    print("\(key): \(value)")

stringsAsInts["three"] = 3 // update
stringsAsInts.updateValue(3, forKey: "three") // You can use the updateValue(forKey:) to update

stringsAsInts.removeValueForKey("three") // removeValueForKey() 

4. What is set?

Answer : Sets are used to store distinct values of same types but they don’t have definite ordering as arrays have

You can use sets instead of arrays if ordering of elements is not an issue, or if you want to ensure that there are no duplicate values. (sets allow only distinct values.)

Declaring a set with duplicate values

let someStrSet:Set = ["ab","bc","cd","de","ab"]

When you run the program, the output will be:

["de", "ab", "cd", "bc"]

5. What is the first thing called when iOS application start

Answer : in main.m file (main function)

But for practical purposes I think you usually need to implement some of the UIApplicationDelegate’s methods, depending on situation:

If an app starts up it’s:

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions :

if A View starts up, then it’s:

- (void)viewDidLoad {}

6. What is the difference between var and let?

Answer:  var is a variable that can be changed (mutable) while let denotes a constant that cannot be changed once set (immutable).

7. What is the difference between implicit and explicit?

Answer:  When referring to something as implicit or explicit, it is often referring to how an object is declared. In the two examples below:

var name: String = "onthecodepath" // explicit
var name = "onthecodepath" // implicit (Swift is able to infer that name is
of a String type since the value that it is being set as is of a String 

8. What is the question mark (optional) ? in Swift?

Answer: The question mark ? is used during the declaration of a property, as it tells the compiler that this property is optional. The property may hold a value or not, in the latter case it’s possible to avoid runtime errors when accessing that property by using ?. This is useful in optional chaining (see below) and a variant of this example is in conditional clauses.

var optionalName : String? = “John" 
if optionalName != nil {   
    print(“Your name is \(optionalName!)”)

9. Type of optional unwrapping in swift?

Answer: 1. Optional binding  2. Force unwrapping  3. guard (early exit)

10. What is Optional binding in swift?

Answer: Use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.

An optional binding for the if statement is as follows −

var myString:String?
myString = "Hello, Swift 4!"

if let yourString = myString {
   print("Your string has - \(yourString)")
} else {
   print("Your string does not have a value")

When we run the above program using playground, we get the following result −

Your string has - Hello, Swift 4!

11. What is the force unwrapping it Swift?

Answer: This is where we are sure an optional has a value. If for some reason we force unwrap an optional that does not, in fact, have a value then this will result in a program crash.

12. What is implicit optional?

Answer: Sometimes we do not provide an initial value for our variable but it is clear from our program’s structure that the variable will have a value. In this case, there is no need to make the variable optional. Instead we make it implicit optional. Implicit optionals are in fact optionals behind the scenes but when they get a value this is unwrapped automatically and the variable does not need to be treated as an optional. If no value exists when we attempt to access an implicit optional this will result in a program crash.

var myName: String!
myName = "Sandesh"

let fullName = myName + "Sardar"

13. What is the use of exclamation mark !?

Answer: Highly related to the previous keywords, the ! is used to tell the compiler that I know definitely, this variable/constant contains a value and please use it (i.e. please unwrap the optional).

14. Optional chaining 

Answer: The process of querying, calling properties, subscripts and methods on an optional that may be ‘nil’ is defined as optional chaining. Optional chaining return two values −

  • if the optional contains a ‘value’ then calling its related property, methods and subscripts returns values
  • if the optional contains a ‘nil’ value all its its related property, methods and subscripts returns nil

Since multiple queries to methods, properties and subscripts are grouped together failure to one chain will affect the entire chain and results in ‘nil’ value.

Program for Optional Chaining with ‘!’

class ElectionPoll {
   var candidate: Pollbooth?

class Pollbooth {
   var name = "MP"

let cand = ElectionPoll()
let candname = cand.candidate!.name

When we run the above program using playground, we get the following result −

fatal error: unexpectedly found nil while unwrapping an Optional value

Program for Optional Chaining with ‘?’

class ElectionPoll {
   var candidate: Pollbooth?

class Pollbooth {
   var name = "MP"
let cand = ElectionPoll()

if let candname = cand.candidate?.name {
   print("Candidate name is \(candname)")
} else {
   print("Candidate name cannot be retreived")

When we run the above program using playground, we get the following result −

Candidate name cannot be retreived

15. How to store data locally?


  • SQLite
  • Property List
  • Core Data
  • NSUser Defaults
  • Key Chain

SQLite For iOS Local Data Storage
SQLite is a powerful lightweight C library that is embedded in an iOS application. This is used in various applications across various platforms including Android and iOS. It uses SQL-centric API to operate the data tables directly.

Property List
Plist files enable storing serialized objects with key/value conventions. In macOS and iOS applications, the most common usage example of plist is an Info.plist file which stores application settings values. Inside Info.plist we can find the application name, bundle identifier, version number,

Documents in property list contain either an NSDictionary or an NSArray, inside which there is archived data.
There are number of classes that can be archived into the Plist, eg. NSArray, NSDate, NSString, NSDictionary. Objects other than these cannot be archived as a property list and will not be able to write the file.
user has to be very particular about listing items into the classes, for instance to store a Boolean or Integer object only NSNumber class is used. Boolean or Integer object must not be given to any objects in NSDictionary or NSArray.

Core Data
By default, core data uses SQLite as its main database in the iOS app.
Internally Core Data make use of SQLite queries to save and store its data locally, which is why all the files are stored as .db files.
This also eliminates the need to install a separate database. Core Data allows you deal with common functionalities of an app like, restorestoreundo and redo.

Core data is a data modelling framework built on the model-view-controller(MVC) pattern. It is expressed in terms of entities and relationships. We can create entities and add relationships in the graphical form.

NSUserDefaults :
To save properties in any application and user preferences, NSUserDefaults is one of the most common methods for local data storage. for ex. this is used to save logged in state of the user within an application, so that the app can fetch this data even when user access the application at some other time. In some of the iOS apps this method is used to save user’s confidential information like access token.

NSUserDefault is used to store small amounts of data. It can slows down app if large data is store. Also UserDefaults is not encrypted.

Key Chain :
It can be used to save passwords, secure notes, certificates, etc. In general, Keychain is an encrypted database with quite a complicated and robust API.

Use to reduce the vulnerabilities of iOS applications, by storing local data in a secure manner.
If the device is jail broken, none of your data is secure. This is the most secure and reliable method to store data on a non-jailbroken device.
Simple wrapper classes are used to store data using key chain method. The code for saving data is similar to the code for saving data in NUserDefaults and the syntax used is very similar to that of NUserDefaults. However, data storage using the keychain is not possible for a jailbroken device, where the attacker can access everything from PList files, key chain and other method implementations.

Saving Files to Disk

Apple makes writing, reading, and editing files inside the iOS applications very easy. Every application has a sandbox directory (called Document directory) where you can store your files. FileManager object provides all these functionalities with very simple APIs.

Diff. Between SQLite and Core data?

Core Data:

  1. Not a database, its a framework for managing object graph (collection of interconnected objects)
  2. It uses SQLite for its persistent store.
  3. Framework excels at managing complex object graphs and its life cycles.
  4. Core Data is an ORM (Object Relational Model) which creates a layer between the database and the UI


  1. Relational database
  2. Lightweight DB and stored on disk
  3. SQLite does not require a separate server process or system to operate.

16. What is delegate and datasource

AnswerA delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program.

The delegating object typically keeps a reference to the other object (delegate) and sends a message to it at the appropriate time. It is important to note that they have a one to one relationship.

A datasource is like a delegate except that, instead of being delegated control of the user interface, it is delegated control of data

TabelView delegate and datasource methods

Datasource :

UITableViewDataSource protocol deal with providing data for the tableview. The required functions that need to be implemented are

- tableView:cellForRowAtIndexPath:
- tableView:numberOfRowsInSection:

Delegate :


CollectionView delegate and datasource methods


cellForItemAt indexPath: IndexPath


didSelectItemAt indexpath 

flow layout works with the collection view’s delegate object to determine the size of items, headers, and footers in each section and grid. That delegate object must conform to the UICollectionViewDelegateFlowLayout protocol. Use of the delegate allows you to adjust layout information dynamically.

17. Struct vs Class in Swift

AnswerClasses and structures are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your classes and structures by using exactly the same syntax as for constants, variables, and functions.

Value Type: Struct , Enum, String, Array , Dictionary

Reference Type: Class, NSString, NSArray

  1. When you pass a class object around your program, you are actually passing a reference to that object, so different parts of your program can share and modify your object. When you pass a structure [ or enum] around your program, what gets passes around is a copy of the structure. So modifications to structures don’t get shared.
  2. Inheritance enables one class to inherit the characteristics of another. Struct or enum cannot do inheritance. But they can confirm to protocols. (Inheritance is not allowed in Struct but creating protocol is allowed)

2. final keyword in class makes class final and do allow any other class to inherit from it

3. override function used to override parent class function in child class.

4. inheritance is not available in struct

5. classes never come with a memberwise initializer. This means if you have properties in your class, you must always create your own initializer.

6. difference between classes and structs is that classes can have deinitializers – code that gets run when an instance of a class is destroyed.

7.The final difference between classes and structs is the way they deal with constants. If you have a constant struct with a variable property, that property can’t be changed because the struct itself is constant.

18. What is the purpose of UIWindow object?

AnswerThe presentation of one or more view on screen is coordinated by UIWindow object.

19. What is App bundle?

AnswerAn iOS app bundle contains the app executable file and supporting resources files such as app icons, image files and localised content.

20. How should one handle errors in Swift?

Answer: In Swift, it’s possible to declare that a function throws an error. It is, therefore, the caller’s responsibility to handle the error or propagate it.

You simply declare that a function can throw an error by appending the throwskeyword to the function name. Any function that calls such a method must call it from a try block.

func canThrowErrors() throws -> String 
//How to call a method that throws an error 
try canThrowErrors()//Or specify it as an optional
let maybe = try? canThrowErrors()

21. What is a guard statement in Swift?

Answer:  It basically evaluates a boolean condition and proceeds with program execution if the evaluation is true. A guard statement always has an else clause, and it must exit the code block if it reaches there.

guard let courses =! else {return}

22. What is Enum ?

Answer: Enum is user defined data type. An enumeration is defined using the enum keyword and they define a common type for a group of related values. For example, given that there are seven colors in the rainbow you could create an enumeration named ColorsOfRainbow and add the seven colors as possible values. Enumerations are useful whenever you find yourself with an if-else ladder.

Enumeration names are written with UpperCamelCase. The enumeration cases are written with smallCamelCase. This is the best practice.

Enumerations can come with prepopulated values. These are known as raw values and these should all be of the same type. When you define an enumeration to have an integer or string values you do not need to explicitly assign a raw value for each case because Swift will do this automatically for you.

Sometimes you need to be able to assign values to enums so they have meaning. This lets you create them dynamically, and also use them in different ways.

For example, you might create a Planet enum that stores integer values for each of its cases:

enum Planet: Int {
    case mercury
    case venus
    case earth
    case mars

Swift will automatically assign each of those a number starting from 0, and you can use that number to create an instance of the appropriate enum case. For example, earth will be given the number 2, so you can write this:

let earth = Planet(rawValue: 2)

Associated value:

As well as storing a simple value, enums can also store associated values attached to each case. This lets you attach additional information to your enums so they can represent more nuanced data.

For example, we might define an enum that stores various kinds of activities:

enum Activity {
    case bored
    case running
    case talking
    case singing

That lets us say that someone is talking, but we don’t know what they talking about, or we can know that someone is running, but we don’t know where they are running to.

Enum associated values let us add those additional details:

enum Activity {
    case bored
    case running(destination: String)
    case talking(topic: String)
    case singing(volume: Int)

Now we can be more precise – we can say that someone is talking about football:

let talking = Activity.talking(topic: "football")


Enumerations are usually used with the switch statement. This allows us to match individual enumeration cases. A switch statement must be exhaustive meaning it should cover every possible case in an enumeration. However, you only need to cover a few enumeration cases if you create a default case in your switch statement.

The keywords break and fallthrough are control flow statements used with enumerations. break causes a switch statement to end its execution immediately and to transfer control to the code after a switch’s closing brace (}). fallthrough will make a switch statement to fall into the next case.


A continue statement ends program execution of the current iteration of a loop statement but does not stop execution of the loop statement.

var sum = 0;
for var i = 0 ; i < 5 ; i++ {
    if i == 4 {
        continue //this ends this iteration of the loop
    sum += i //thus, 0, 1, 2, and 3 will be added to this, but not 4


A break statement ends program execution of a loop, an if statement, or a switch statement.

var sum = 0;
for var i = 0 ; i < 5 ; i++ {
    if i == 2 {
        break //this ends the entire loop
    sum += i //thus only 0 and 1 will be added


A fallthrough statement causes program execution to continue from one case in a switch statement to the next case.

var sum = 0
var i = 3
switch i {
case 1:
    sum += i
case 2:
    sum += i
case 3:
    sum += i
    fallthrough //allows for the next case to be evaluated
case i % 3:
    sum += i

Sometimes it is useful to have a value stored with an enumeration case. This is called an associated value and this can be any type that you define.

23. What is static variable?

Answer: Static variables are those variables whose values are shared among all the instance or object of a class. When we define any variable as static, it gets attached to a class rather than an object. The memory for the static variable will be allocation during the class loading time.

static variable can’t be override

we can directly call variable using class name (Animal.nums) (also called instance property) instead of using object name (dog.nums)

Sharing information

class Animal {
    static var nums = 0
    init() {
        Animal.nums += 1
let dog = Animal()
Animal.nums // 1
let cat = Animal()
Animal.nums // 2

As you can see here, I created 2 separate instances of Animal but both do share the same static variable nums.


Often a static constant is used to adopt the Singleton pattern. In this case we want no more than 1 instance of a class to be allocated. To do that we save the reference to the shared instance inside a constant and we do hide the initializer.

class Singleton {
    static let sharedInstance = Singleton()
    private init() { }
    func doSomething() { }

24. Enumerate items in an array

Answer: There several ways to loop through an array in Swift, but using the enumerated() method is one of my favorite because it iterates over each of the items while also telling you the items’s position in the array.

Here’s an example:

let array = ["Apples", "Peaches", "Plums"]
for (index, item) in array.enumerated() {
    print("Found \(item) at position \(index)")

That will print “Found Apples at position 0”, “Found Peaches at position 1”, and “Found Plums at position 2”.

25. Didset/willset

Answer: property observers, which let you execute code whenever a property has changed. To make them work, we use either didSet to execute code when a property has just been set, or willSet to execute code before a property has been set

var score = 0 {
    didSet {
        scoreLabel.text = "Score: \(score)"

Using this method, any time score is changed by anyone, our score label will be updated

26. Mutating Functions

Answer: In swift, classes are reference type whereas structures and enumerations are value typesThe properties of value types cannot be modified within its instance methods by default. In order to modify the properties of a value type, you have to use the mutating keyword in the instance method. With this keyword, your method can then have the ability to mutate the values of the properties and write it back to the original structure when the method implementation ends.

Below is a simple implementation of Stack in Swift that illustrates the use of mutating functions.

struct Stack {
    public private(set) var items = [Int]() // Empty items array
    mutating func push(_ item: Int) {
    // if we dont write mutating it will give compile time error
    mutating func pop() -> Int? {
        if !items.isEmpty {
           return items.removeLast()
        return nil

var stack = Stack()
stack.items // [4, 78]
stack.items // [4]

27. Diff. in Points and Pixels – The Reason We Need @2x and @3x Icons

Answer: The Problem of Higher Pixel Density

Why do we have to create @2x and @3x icons? Well, not too long ago, all iPhones had a standard resolution. However, all this changed when the iPhone 4 was released. The iPhone 4 came with retina display with twice as many pixels as before. More pixels meant that graphics appeared clearer to users but what this also meant was that graphics on a non-retina device will smaller on a retina display. For example, a 100px by 100px image on a non-retina device would look like a 50px by 50px image even though its actual size is still 100px by 100px. Things only got worse with the introduction of the iPhone 6 Plus which had three times as many pixels as the older devices.

How Points Solved Differing Pixel Densities

To ensure that graphics displayed at the correct size regardless of device, Apple came up with the system of points. A point is a device independent measurement. On non-retina devices 1 point is equal to 1 pixel. On retina devices like iPhone 4, 5 and 6 – 1 point is equal to 2 pixels. And on much larger devices like iPhone 6 Plus with higher pixel density 1 point is equal to 3 pixels.

28. Why don’t we use strong for enum property in Objective-C ?

Answer: Because enums aren’t objects, so we don’t specify strong or weak here

29. What is super keyword

Answer: ‘super’ keyword is used as a prefix to access the methods, properties and subscripts declared in the super class

class Circle {
   var radius = 12.5
   var area: String {
      return "of rectangle for \(radius) "

class Rectangle: Circle {
   var print = 7
   override var area: String {
      return super.area + " is now overridden as \(print)"

30. Outline the class hierarchy for a UIButton until NSObject.

Answer: UIButton inherits from UIControl, UIControl inherits from UIView, UIView inherits from UIResponder, UIResponder inherits from the root class NSObject.

NSObject is called universal base class for all cocoa touch classes

31. What is reuseIdentifier?

Answer: The reuseIdentifier is used to indicate that a cell can be re-used in a UITableView. For ex. when the cell looks the same, but has different content. The UITableView will maintain an internal cache of UITableViewCell’s with the reuseIdentifier and allow them to be re-used when dequeueReusableCellWithIdentifier: is called. By re-using table cell’s the scroll performance of the tableview is better because new views do not need to be created.

32. What’s Completion Handler ? 

Answer: Completion handlers are super convenient when our app is making an API call, and we need to do something when that task is done, like updating the UI to show the data from the API call. We’ll see completion handlers in Apple’s APIs like dataTaskWithRequest and they can be pretty handy in your own code.

The completion handler takes a chunk of code with 3 arguments:(NSData?, NSURLResponse?, NSError?) that returns nothing: Void. It’s a closure.

The completion handlers have to marked @escaping since they are executed some point after the enclosing function has been executed.

33. Explain the difference between atomic and nonatomic synthesized properties?

Answer:  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. Hence in some situations nonatomic is used to provide faster access to a property, but there is a chance of a race condition causing the property to be nil under rare circumstances (when a value is being set from another thread and the old value was released from memory but the new value hasn’t yet been fully assigned to the location in memory for the property).

  • Atomic is the default: if you don’t type anything, your property is atomic. An atomic property is guaranteed that if you try to read from it, you will get back a valid value. It does not make any guarantees about what that value might be, but you will get back good data, not just junk memory. What this allows you to do is if you have multiple threads or multiple processes pointing at a single variable, one thread can read and another thread can write. If they hit at the same time, the reader thread is guaranteed to get one of the two values: either before the change or after the change. What atomic does not give you is any sort of guarantee about which of those values you might get. Atomic is really commonly confused with being thread-safe, and that is not correct. You need to guarantee your thread safety other ways. However, atomic will guarantee that if you try to read, you get back some kind of value.
  • On the flip side, non-atomic, as you can probably guess, just means, “don’t do that atomic stuff.” What you lose is that guarantee that you always get back something. If you try to read in the middle of a write, you could get back garbage data. But, on the other hand, you go a little bit faster. Because atomic properties have to do some magic to guarantee that you will get back a value, they are a bit slower. If it is a property that you are accessing a lot, you may want to drop down to nonatomic to make sure that you are not incurring that speed penalty.

34. Which API would you use to write test scripts to exercise the application’s UI elements?

Answer:  UI Automation API is used to automate test procedures. JavaScript test scripts that are written to the UI Automation API simulate user interaction with the application and return log information to the host computer.

36. Which is the application thread from where UIKit classes should be used? 

Answer: UIKit classes should be used only from an application’s main thread.

37. What is Responder Chain ?

Answer: A ResponderChain is a hierarchy of objects that have the opportunity to respond to events received.

When an event happens in a view, for example a touch event, the view will fire the event to a chain of UIResponder objects associated with the UIView. The first UIResponder is the UIViewitself, if it does not handle the event then it continues up the chain to until UIResponder handles the event. The chain will include UIViewControllers, parent UIViews and their associated UIViewControllers, if none of those handle the event then the UIWindow is asked if it can handle it and finally if that doesn’t handle the event then the UIApplicationDelegate is asked.

enter image description here

38- What is Regular expressions ?

Answer: Regular expressions are special string patterns that describe how to search through a string. ex. regular expression for strong password, RE for correct mobile number.

39. What is Functions ?

Answer: Functions let us group a series of statements together to perform some task. Once a function is created, it can be reused over and over in your code. If you find yourself repeating statements in your code, then a function may be the answer to avoid that repetition.

Pro Tip, Good functions accept input and return output. Bad functions set global variables and rely on other functions to work.`

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

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

41.What considerations do you need when writing a UITableViewController which shows images downloaded from a remote server?


  • Only download the image when the cell is scrolled into view (when cellForRowAtIndexPath is called)
  • Download the image asynchronously on a background thread so as not to block the UI so the user can keep scrolling
  • When the image has downloaded for a cell, check if that cell is still in the view or whether it has been re-used by another piece of data. If the cell has been re-used, then the image should be discarded. Otherwise, it should be switched back to the main thread to change the image on the cell.
  • Can cache downloaded images if its not available in cache.

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

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

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

Answer: 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”]

44. What’s your preference when writing UI’s? Xib files, Storyboards or programmatic UIView?

Answer: There’s no right or wrong answer to this, but it’s great way of seeing if you understand the benefits and challenges with each approach. Here’s the common answers I hear:

  • Storyboard’s and Xib’s are great for quickly producing UI’s that match a design spec. They are also really easy for product managers to visually see how far along a screen is.
  • Storyboard’s are also great at representing a flow through an application and allowing a high-level visualizations of an entire application.
  • Storyboard’s drawbacks are that in a team environment they are difficult to work on collaboratively because they’re a single file and merge’s become difficult to manage.
  • Storyboards and Xib files can also suffer from duplication and become difficult to update. For example if all button’s need to look identical and suddenly need a color change, then it can be a long/difficult process to do this across storyboards and xibs.
  • Programmatically constructing UIView’s can be verbose and tedious, but it can allow for greater control and also easier separation and sharing of code. They can also be more easily unit tested.

Most developers will propose a combination of all 3 where it makes sense to share code, then re-usable UIViews or Xib files.

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


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

With SSL pinning, we can refuse all connections except the ones with the designated server whose SSL certificate we’ve saved into our local bundle middle of the communication between the device U and router Rand it can eavesdrop or block it. IP forwarding is often used on the attacker’s device to keep the communication flowing seamlessly between the user’s device and router. Things are a bit more tricky when it comes toNSURLSession SSL pinning. There is no way to set an array of pinned certificates and cancel all responses that don’t match our local certificate automatically. We need to perform all checks manually to implement SSL pinning onNSURLSession. Alomfire there is one method ServerTrustPolicy.certificatesInBundle() method which returns all the certificates within the bundle. By default,AFNetworking will scan through your bundle and check for all “.cer” files, and add them to the manager.securityPolicy.pinnedCertificates array With the release of the iOS 9, the App Transport Security library was also introduced. By default, ATS denies all insecure connections which do not use at least the TLS 1.2 protocol.

46. What is Autorelease pool?

Answer:  The concept of an autorelease pool is simple, whenever an object instance is marked as autoreleased (for example NSString*str = [[[NSString alloc] initWithString:@”hello”] autorelease];), it will have a retain count of +1 at that moment in time, but at the end of the run loop, the pool is drained, and any object marked autorelease then has its retain count decremented. It’s a way of keeping an object around while you prepare whatever will retain it for itself.

47. What is ViewLifeCycle?

Answer:  loadView viewDidLoad viewWillAppear viewWillLayoutSubviews viewDidLayoutSubviews viewDidAppear

48. What is Design Pattern?

Answer:  viewController is tightly coupled because of viewLifecycle MVC, MVP(uikit independent mediator) , MVVM (mediator is VM and UIKITindependant) Viper – granularity in responsibilities is very good (view interactor presenter entity router)

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

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

50. What is AutoLayout? What does it mean when a constraint is “broken” by iOS?

Answer:  AutoLayout is way of laying out UIViews using a set of constraints that specify the location and size based relative to other views or based on explicit values. AutoLayout makes it easier to design screens that resize and layout out their components better based on the size and orientation of a screen. _Constraint_s include:

  • setting the horizontal/vertical distance between 2 views
  • setting the height/width to be a ratio relative to a different view
  • a width/height/spacing can be an explicit static value

Sometimes constraints conflict with each other. For example imagine a UIView which has 2 height constraints: one says make the UIView 200px high, and the second says make the height twice the height of a button. If the iOS runtime can not satisfy both of these constraints then it has to pick only one. The other is then reported as being “broken” by iOS.

51. What is the difference between Synchronous & Asynchronous task ?

Answer:  Synchronous waits until the task has completed. Asynchronous: completes a task in background and can notify you when complete

52. Security updates in iOS 10

Answer:  App Transport Security (ATS) was introduced in iOS 9 as a built in utility for protecting network communications, namely connections which use the NSURLSession and NSURLConnection APIs. Out of the box, ATS enforces a TLS configuration with the following criteria:

  • Apps must connect to servers using the TLS 1.2 protocol
  • server must use HTTPS protocol

Important, by the end of 2016, Apple will enforce the use of ATS during App Store approval. It is therefore very important that engineering teams start to roadmap migration to securer HTTPS configurations as soon as possible. As a developer, you can still configure exceptions in the ATS configuration, but you will be required to provide a justification in the app store review as to why you require the exception. During the “What’s new in Security WWDC16 session”, Apple stated that one example use case for exceptions might be when you communicate with a 3rd party and don’t have control over their HTTPS configuration. Another example is when an Application communicates dynamically to various internet sites such as within a WebView. A 3rd example of an exception might be because the domain you want to communicate with does not offer Perfect Forward Secrecy.

ATS required by 2017

App Transport Security was introduced last year and by default blocks “unprotected” connections initiated by Apps, ie. connections that do not use HTTPS with the strongest TLS version and cipher suites. Because switching servers to the strongest TLS configuration takes time, Apple also allowed App developers to selectively disable ATS requirements by adding exemptions in the App’s Info.plist.

Purpose strings required

When built for iOS 10, an App will crash if it tries to request access for a data class that does not have a purpose string defined. Purpose string keys where introduced in iOS 6; there is one key defined for each type of privacy-sensitive data (contacts, camera, photo library, etc.). App developers can add these keys to the App’s Info.plist to provide a sentence that explains why the App needs access to the data; the explanation then gets displayed in the user-facing permission prompt: Not providing a purpose string will now crash the App when the permission prompt was going to be displayed. Apple made this change for two reasons:

  • It forces App developers to inform the user about the reason why the App needs access to the data.
  • It prevents third-party SDKs within the App from requesting access to data the App developers never intended to access in the first place.

Additionally, there are several new consent alerts in iOS 10, with a corresponding purpose string:

  • Media Library, for allowing access to Apple Music subscriber status and playlists.
  • Speech Recognition, for allowing audio files to be sent to Apple for speech transcription done on behalf of the App.
  • SiriKit, for allowing the App to receive Siri requests.
  • TV Provider information (tvOS only), for automatically logging the user into streaming Apps based on their cable subscription.

53. What is the difference between public and open? Why is it important to have both?

Answer:  Open access imposes limitations on class inheritance. Classes declared with open level access can be subclassed by modules they are defined in, modules that import the module in which the class is defined, and class members as well. While this sounds similar to the public access level defined in Swift 2, there is a small difference. In Swift 3, the meaning of public access level means that classes declared public can only be subclassed in the module they are defined in. This includes public class members which can be overridden by subclasses defined in the module they are defined in.

Some classes of libraries and frameworks are not designed to be subclasses. For example, in the Core Data framework, Apple states that some methods of NSManagedObject should not be overridden. To prevent any unexpected behavior that may result from overriding those methods, Apple declares those methods public rather than open. As a result, those methods are not marked as open for developers to override.

54. What is waterfall methodology and Agile methodology? What are the differences between them?

Answer:  Waterfall methodology is a sequential model for software development. It is separated into a sequence of pre-defined phases including feasibility, planning, design, build, test, production, and support.

On the other hand, Agile development methodology is a linear sequential approach that provides flexibility for changing project requirements.

List of differences:

  • Waterfall model divides software development process into different phases while Agile segregates the project development lifecycle into sprints. This makes waterfall more rigid while agile allows for more flexibility
  • Waterfall model describes the software development life cycle as a single project while Agile considers it as a collection of many different projects; are iterations of different phases focusing on improving overall software quality with feedback from users and QA team.
  • Since waterfall is more rigid, development requirements need to be clearly established beforehand since there is little flexibility for changing once project development starts. Meanwhile, Agile allow changes to be made anytime along the project development process even after initial planning has been completed.
  • In Waterfall, the testing phase typically occurs after the build phase. In Agile, testing is often performed concurrently with programming or at least in the same iteration.
  • Waterfall is more of an internal process that does not involve user feedback. Agile tends to involve user participation more in order to improve customer satisfaction.
  • Waterfall model best fits projects that have a clearly defined set of requirements and where change to requirements is not expect. Agile fits more for projects where the requirements are expected to change and evolve.
  • Waterfall can exhibit a project mindset that focuses on completion of the project while Agile can allow for more focus on developing a product that satisfies customers.

55. What is the difference between a class and an object?

Answer:  In the simplest sense, a class is a blueprint for an object. It describes the properties and behaviours common to any particular type of object. An object, on the other hand, is an instance of a class.

56. Is it faster to iterate through an NSArray or an NSSet?

Answer:  It depends. NSSet is faster to iterate through if the order of the items in the collection is not important. The reason is because NSSet uses hash values in order to find items while NSArray has to iterate through its entire contents to find a particular object.

59. Generics

Answer: ‘Generic’ features to write flexible and reusable functions and types. Generics are used to avoid duplication.

for ex. if we want to swap two values (which can be int, string, double) so instead of wring diff functions for string, int, double we can create generic function

func exchange<T>(a: inout T, b: inout T) {
   let temp = a
   a = b
   b = temp
var numb1 = 100
var numb2 = 200

print("Before Swapping Int values are: \(numb1) and \(numb2)")
exchange(a: &numb1, b: &numb2)
print("After Swapping Int values are: \(numb1) and \(numb2)")

var str1 = "Generics"
var str2 = "Functions"

print("Before Swapping String values are: \(str1) and \(str2)")
exchange(a: &str1, b: &str2)
print("After Swapping String values are: \(str1) and \(str2)")

Memory Management

What is memory leak?

A memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. In object-oriented programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code.

60. What is the difference between weak and strong, read only, copy, Retain, unowned ?

Answer: Weak self and unowned self in Swift for many of us are hard to understand. Although Automatic Reference Counting (ARC) solved a lot for us already, we still need to manage references when we’re not working with value types.

First, objects are strong by default.

  • Strong means that the reference count will be increased and the reference to it will be maintained throughout the life of the object.
  • Weak, means that we are pointing to an object but not increasing its reference count. It’s often used when creating a parent child relationship. The parent has a strong reference to the child but the child only has a weak reference to the parent. (source)
  • weak will nullify the pointer whenever the reference is deallocated but unowned won’t do that, so that may results in dangling pointer.

    Because weak references need to allow their value to be changed to nil at runtime, they are always declared as variables and optional

    if let and not optional use unowned

     weak var customer: Customer?

Weak and unowned are used to solve leaked memory and retain cycles. Both do not increase the retain count.

Common instances of weak references are delegate properties and subview/controls of a view controller’s main view since those views are already strongly held by the main view.

Read only, we can set the property initially but then it can’t be changed.

Copy, means that we’re copying the value of the object when it’s created. Also prevents its value from changing.

Retain: Retaining an object means the retain count increases by one. This means the instance of the object will be kept in memory until it’s retain count drops to zero. The property will store a reference to this instance and will share the same instance with anyone else who retained it too.


You could use unowned when the other instance has same life time or longer lifetime.

Take an example of Customer and CreditCard. Here, CreditCard cannot exist without a customer. A CreditCard instance never outlives the Customer that it refers to, And we only create a CreditCard instance by passing Customer instance in the initialiser. So we can absolutely guarantee that this CreditCard cannot exist without the Customer.

61. What is tuple in swift?

Answer: Tuple is used to group multiple values in a single compound Value. The values in a tuple can be of any type, and do not need to be of same type. For example, (“Tutorials Point”, 123)

Design Pattern

62. Why is design pattern very important ?

Answer: Design patterns are reusable solutions to common problems in software design. They’re templates designed to help you write code that’s easy to understand and reuse. Most common Cocoa design patterns:

  • Creational: Singleton.
  • Structural: Decorator, Adapter, Facade.
  • Behavioral: Observer, and, Memento

63. What is extension and why to use?

Answer: Swift Extension is a useful feature that helps in adding more functionality to an existing Class, Structure, Enumeration or a Protocol type. This includes adding functionalities for types where you don’t have the original source code too (extensions for Int, Bool etc.)

for ex. extension for alertcontroller which has function which takes parameter for title and message so that we can use this in multiple places instead of writing whole alertcontroller code everywhere.

extension Int {
    var square : Int{
        return self*self
    func cube()->Int{
        return self*self*self
    mutating func incrementBy5() {
        self = self + 5

var x : Int = 5
print(x.square) //prints "25\n"
print(x.cube()) //prints "125\n"
x.incrementBy5() // 10

64. What is MVC?

Answer:  MVC stands for Model-View-Controller. It is a software architecture pattern for implementing user interfaces.

MVC consists of three layers: the model, the view, and the controller.

  • The model layer is typically where the data resides (persistence, model objects, etc)
  • Database model layer takes data from database and process on it
  • The view layer is typically where all the UI interface lies. Things like displaying buttons and numbers belong in the view layer. The view layer does not know anything about the model layer and vice versa.
  • The controller (view controller) is the layer that integrates the view layer and the model layer together.

Real life example: Example of restaurant 

Inventory is a database where all groceries are stored. (ingredients for pizza)
Kitchen is a model where groceries (data) is processed (to make pizza) taken from Inventory (database) as per required to present to a customer (view). (prepare pizza fro)
Waiter is Controller who communicates with a customer(view) and chef (model)
Customer or table is a view where processed food (data) is presented by a waiter (controller)
here customer (view) don’t go directly in kitchen (model)

65. What is MVVM?

Answer:  MVVM stands for Model-View-ViewModel. It is a software architecture pattern for implementing user interfaces.

MVVM is an augmented version of MVC where the presentation logic is moved out of the controller and put into the view model. The view model is responsible for handling most, if not all, of the view’s display logic.

A common occurence in MVC is where you have a massive-view-controller (some joke this is what MVC stands for). In order to shrink the size of your view controller and make the logic and readability of your code easier to follow along, the MVVM will be used.

Design, View, Storyboard 

66. What’s the difference between the frame and the bounds?

Answer: The frame of a UIView is the region relative to the superview it is contained within while the bounds of a UIView is the region relative to its own coordinate system..

67. Which are the ways of achieving concurrency in iOS?

Answer: The three ways to achieve concurrency in iOS are:

  • Threads
  • Dispatch queues
  • Operation queues

Thread management

68. What is threads?

Answer: behind the scenes your app actually executes multiple sets of instructions at the same time, which allows it to take advantage of having multiple CPU cores (iOS has CPU 6 cores). Each CPU can be doing something independently of the others, which hugely boosts your performance. These code execution processes are called threads,

Threads execute the code you give them, they don’t just randomly execute a few lines from viewDidLoad() each. This means by default your own code executes on only one CPU, because you haven’t created threads for other CPUs to work on.

All user interface work must occur on the main thread, which is the initial thread your program is created on.

You don’t get to control when threads execute, or in what order. You create them and give them to the system to run, and the system handles executing them as best it can.

if all user interface code must run on the main thread, and we just blocked the main thread by using Data‘s contentsOfor service call, it causes the entire program to freeze – the user can touch the screen all they want, but nothing will happen.

Broadly speaking, if you’re accessing any remote resource, you should be doing it on a background thread – i.e., any thread that is not the main thread. If you’re executing any slow code, you should be doing it on a background thread. If you’re executing any code that can be run in parallel – e.g. adding a filter to 100 photos – you should be doing it on multiple background threads.

The power of GCD is that it takes away a lot of the hassle of creating and working with multiple threads, known as multithreading. You don’t have to worry about creating and destroying threads, and you don’t have to worry about ensuring you have created the optimal number of threads for the current device. GCD automatically creates threads for you, and executes your code on them in the most efficient way it can.

To fix our project, you need to learn three new GCD functions, but the most important one is called async() – it means “run the following code asynchronously,” i.e. don’t block (stop what I’m doing right now) while it’s executing. Yes, that seems simple, but there’s a sting in the tail: you need to use closures.

69. What is the difference between synchronous and asynchronous task?

Answer: Synchronous tasks wait until the task has been completed while asynchronous tasks can run in the background and send a notification when the task is complete.

70. Explain the difference between Serial vs Concurrent

Answer: Tasks executed serially are executed one at a time while tasks that are executed concurrently may be executed at the same time.

71. What is GCD and how is it used? – concept

GCD stands for Grand Central Dispatch.  It offers the following benefits

  • Improving your app’s responsiveness by helping to defer computationally expensive tasks and run them in the background.
  • Providing an easier concurrency model than locks and threads and helps to avoid concurrency bugs.
  • Potentially optimize your code with higher performance primitives for common patterns such as singletons.

In other words, GCD provides and manages queues of tasks in the iOS app. This is one of the most commonly used API to manage concurrent code and execute operations asynchronously. Network calls are often performed on a background thread while things like UI updates are executed on the main thread.

GCD creates for you a number of queues, and places tasks in those queues depending on how important you say they are. All are FIFO, meaning that each block of code will be taken off the queue in the order they were put in, but more than one code block can be executed at the same time so the finish order isn’t guaranteed.

“How important” some code is depends on something called “quality of service”, or QoS, which decides what level of service this code should be given. Obviously at the top of this is the main queue, which runs on your main thread, and should be used to schedule any work that must update the user interface immediately even when that means blocking your program from doing anything else. But there are four background queues that you can use, each of which has their own QoS level set:

  1. User Interactive: this is the highest priority background thread, and should be used when you want a background thread to do work that is important to keep your user interface working. This priority will ask the system to dedicate nearly all available CPU time to you to get the job done as quickly as possible.
  2. User Initiated:  this should be used to execute tasks requested by the user that they are now waiting for in order to continue using your app. It’s not as important as user interactive work – i.e., if the user taps on buttons to do other stuff, that should be executed first – but it is important because you’re keeping the user waiting.
  3. The Utility queue: this should be used for long-running tasks that the user is aware of, but not necessarily desperate for now. If the user has requested something and can happily leave it running while they do something else with your app, you should use Utility.
  4. The Background queue: this is for long-running tasks that the user isn’t actively aware of, or at least doesn’t care about its progress or when it completes.

Those QoS queues affect the way the system prioritizes your work: User Interactive and User Initiated tasks will be executed as quickly as possible regardless of their effect on battery life, Utility tasks will be executed with a view to keeping power efficiency as high as possible without sacrificing too much performance, whereas Background tasks will be executed with power efficiency as its priority.

72. NSOperationQueue :

Answer:  NSOperationQueue is objective C wrapper over GCD .

we can set priority to each queue. and can start stop and pause operation if one task is depends on another. It use for complex thing

73. What is dispatch queues?

Answer:  Dispatch queues are an easy way to perform tasks asynchronously and concurrently in your application

Unit testing, UI testing

73. XCTest –

XCTAssertEqual, XCTAssertNotNil, XCTAssertTrue

74. What’s Code Coverage ?

Answer: Code coverage is a tool that helps us to measure the value of our unit tests.

75. What is setUp() and tearDown() in unit testing?


  1. setUp() — This method is called before the invocation of each test method in the given class.
  2. tearDown() — This method is called after the invocation of each test method in given class.

Objective c –

76. Explain what is @synthesize in Objective-C?

Answer: Once you have declared the property in objective-C, you have to tell the compiler instantly by using synthesize directive. synthesize generates getter and setter methods for your property.

77. What is @dynamic in Objective-C ?

Answer:  Dynamic for properties means that it setters and getters will be created manually and/or at runtime. We can use dynamic not only for NSManagedObject.

78. Why do we use synchronized?

Answer: synchronized guarantees that only one thread can be executing that code in the block at any given time.

79. What is the difference between category and extension in Objective-C?

Answer: A category and extension are similar in functionality where they can add additional instance and class methods to a class. However, an extension can only do so if the source code for the class being extended is available at compile time. This means that classes such as NSString cannot be extended. Instead, a category would be used to add additional methods to the NSString class

80. Access controls in Swift


Access controls 
keyword enables you to hide the implementation details of your code, and to specify a preferred interface through which that code can be accessed and used.

There are 5 access controls:
1. open (most accessibleleast restrictive)
2. public
3. internal (default)
4. fileprivate
5. private (least accessiblemore restrictive)

1. open : It enable entity to be used in and outside of defining module and also other module. UIButton, UITableView is in UIKit. We import UIKit and make subclass of UITableView and use in our module in which we have imported UIKit. So tableview subclass of UITableView defined in UIKit is used in our module. Sot it is accessible in our module.

open class UITableView : UIScrollView, NSCoding { }


2. public : open allows us to subclass from another module. public allows us to subclass or override from within module in which it defined.

public func A(){} //module X 
open func B(){}//module Y 

override func A(){} // error 
override func B(){} // success

So open class and class members can be accessible and overridden in which it is defined and also in which module it is imported.
public class and class members can be accessible and overridden only in which it is defined.

3. internal : Internal classes and members can be accessed anywhere within the same module(target) they are defined. You typically use internal-access when defining an app’s or a framework’s internal structure.

4. fileprivate : Restricts the use of an entity to its defining file. It is used to hide implementation details when details are used in entire file. fileprivate method is only accessible from that swift file in which it is defined.

5. private : Restricts the use of an entity to the enclosing declaration and to extension of that swift file or class. It is used to hide single block implementation.

Design pattern 

81. What do you know about singletons? Where would you use one and where would you not?

Answer:  Singleton is a class that returns only one and the same instance no matter how many times you request it.

Singletons are sometimes considered to be an anti-pattern. There are multiple disadvantages to using singletons. The two main ones are global state/statefulness and object life cycle and dependency injection. When you have only one instance of something, it is very tempting to reference and use it everywhere directly instead of injecting it into your objects. That leads to unnecessary coupling of concrete implementation in your code instead of interface abstraction.
Another malicious side effect of “convenient” singletons is global state. Quite often singletons enable global state sharing and play the role of a “public bag” that every object uses to store some state. That leads to unpredictable results and bugs and crashes when this uncontrolled state gets overridden or removed by someone.

Ex. We can use singleton in game where we want to store score.

82. Could you explain what the difference is between Delegate and KVO?

Answer:  Both are ways to have relationships between objects. Delegation is a one-to-one relationship where one object implements a delegate protocol and another uses it and sends messages to it, assuming that those methods are implemented since the receiver promised to comply to the protocol. KVO is a many-to-many relationship where one object could broadcast a message and one or multiple other objects can listen to it and react. KVO does not rely on protocols. KVO is the first step and the fundamental block of reactive programming (RxSwift, ReactiveCocoa, etc.)

 What’s the difference between using a delegate and notification?

Both are used for sending values and messages to interested parties. A delegate is for one-to-one communication and is a pattern promoted by Apple. In delegation, the class raising events will have a property for the delegate and will typically expect it to implement some protocol. The delegating class can then call the delegates protocol methods.

Notification allows a class to broadcast events across the entire application to any interested parties. The broadcasting class doesn’t need to know anything about the listeners for this event, therefore notification is very useful in helping to decouple components in an application.  Most people use this for receiving system messages, for example to be notified when they keyboard appears or disappears, but you can also use it to send your own messages inside your app.

App Lifecycle 

83. What’s the difference between not-running, inactive, active, background and suspended execution states?


  • Not running: The app has not been launched or was running but was terminated by the system.
  • Inactive:  The app is running in the foreground, but not receiving events (It may be executing other code though.) . An iOS app can be placed into an inactive state, for example, when a call or SMS message is received or user locks the screen.
  • Active: The app is running in the foreground and is receiving events. 
  • Background: 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.
  • Suspended: 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.
For maintaining above states, there are following app delegate methods:
application:willFinishLaunchingWithOptions (First method)
Method called when the launch process is initiated. This is the first opportunity to execute any code within the app.
Method called when the launch process is nearly complete. Since this method is called is before any of the app’s windows are displayed, it is the last opportunity to prepare the interface and make any final adjustments.
Once the application has become active, the application delegate will receive a callback notification message via the method applicationDidBecomeActive.
This method is also called each time the app returns to an active state from a previous switch to inactive from a resulting phone call or SMS.
 Each time a temporary event, such as a phone call, happens this method gets called. It is also important to note that “quitting” an iOS app does not terminate the processes, but rather moves the app to the background.
This method is called when an iOS app is running, but no longer in the foreground. In other words, the user interface is not currently being displayed. According to Apple’s UIApplicationDelegate Protocol Reference, the app has approximately five seconds to perform tasks and return. If the method does not return within five seconds, the application is terminated.
This method is called as an app is preparing to move from the background to the foreground. The app, however, is not moved into an active state without the applicationDidBecomeActive method being called. This method gives a developer the opportunity to re-establish the settings of the previous running state before the app becomes active.
This method notifies your application delegate when a termination event has been triggered. Hitting the home button no longer quits the application. Force quitting the iOS app, or shutting down the device triggers the applicationWillTerminate method. This is the opportunity to save the application configuration, settings, and user preferences.

86. View Lifecycle

Answer: A View Controller manages a set of views and helps in making the application’s user interface. It coordinates with model objects and other controller objects. It is known for playing the role for both view objects and controller objects. Each view controller displays its own views for the app content. The views are loaded automatically when the user accesses the view property of view controller in the app. Let’s focus on the events required to load a view.

> Lifecycle events order


How can we use them?

– init

While creating the views of your app in a Storyboard, init(coder:) is the method that gets called to instantiate your view controller and bring it to life. During the initial phase of a view controller, you usually allocate the resources that the view controller will need during its lifetime. In this method, you might instantiate dependencies, including subviews that you’ll add to your view programmatically. And note that init(coder:) is called only once during the life of the object, as all init methods are.

– LoadView

It is only called when the view controller is created and only when done programatically. You can override this method in order to create your views manually. This is the method that creates the view for the view controller. If you are working with storyboards or nib files, then you do not have to anything with this method and you can ignore it. Its implementation in UIViewController loads the interface from the interface file and connects all the outlets and actions for you.

– viewDidLoad

[super viewDidLoad];
It’s only called when the view is created. Keep in mind that in this lifecycle step the view bounds are not final. Good place to init and setup objects used in the viewController. When this method gets called, the view of the view controller has been created and you are sure that all the outlets are in place. It is also a good place where to start some background activity where you need to have the user interface in place at the end. A common case are network calls that you need to do only once when the screen is loaded. This method is called only once in the lifetime of a view controller, so you use it for things that need to happen only once.

– viewWillAppear

You override this method for tasks that require you to repeat every time a view controller comes on screen. Keep in mind that this method can be called several times for the same instance of a view controller. This event is called every time the view appears and so, there is no need to add code here, which should be executed just one time. Usually you use this method to update the user interface with data that might have changed while the view controller was not on the screen. You can also prepare the interface for animations you want to trigger when the view controller appears.

– viewDidAppear

This method gets called after the view controller appears on screen. You can use it to start animations in the user interface, to start playing a video or a sound, or to start collecting data from the network. In some cases can be a good place to load data from core data and present it in the view or to start requesting data from a server.

– didReceiveMemoryWarning

iOS devices have a limited amount of memory and power. When the memory starts to fill up, iOS does not use its limited hard disk space to move data out of the memory like a computer does. If your app starts using too much memory, iOS will notify it. Since view controllers perform resource management, these notifications are delivered to them through this method. In this way you can take actions to free some memory. Keep in mind that if you ignore memory warnings and the memory used by your app goes over a certain threshold, iOS will end your app means this will look like a crash to the user and should be avoided.

– viewWillDisappear

Before the transition to the next view controller happens and the origin view controller gets removed from screen, this method gets called. You rarely need to override this method since there are few common tasks that need to be performed at this point, but you might need it.

– viewDidDisappear

After a view controller gets removed from the screen, this method gets called. You usually override this method to stop tasks that are should not run while a view controller is not on screen. For example, you can stop listening to notifications, observing other objects properties, monitoring the device sensors or a network call that is not needed anymore.

Memory management

87. How is memory management handled in iOS?

Answer: Swift uses Automatic Reference Counting (ARC). This is conceptually the same thing in Swift as it is in Objective-C. ARC keeps track of strong references to instances of classes and increases or decreases their reference count accordingly when you assign or unassign instances of classes (reference types) to constants, properties, and variables. It deallocates memory used by objects whose reference count dropped to zero. ARC does not increase or decrease the reference count of value types because, when assigned, these are copied. By default, if you don’t specify otherwise, all the references will be strong references.

App deployment 

88.  Diff. between Bundle ID and App ID


  1. A Bundle ID precisely identifies a single app.

A bundle ID or bundle identifier uniquely identifies an application in Apple’s ecosystem. This means that no two applications can have the same bundle identifier. To avoid conflicts, Apple encourages developers to use reverse domain name notation for choosing an application’s bundle identifier.

For example, if your organization’s domain is and you create an app named Hello, you could assign the string as your app’s bundle ID.

2. App ID

An App ID is a two-part string used to identify one or more apps from a single development team. The string consists of a Team ID and a bundle ID search string, with a period (.) separating the two parts. 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.

App id is a combination of two strings, are separated by a period (.). String1 is a team id, Which is assigned to the development team.(provided by apple) String2 is a bundle id, is selected by you.

App id is having two types.

  1. Explicit App ID: Here team id is used to match only one app with a specific bundle id. This app id is used to match one app only. example: TEAM_ID.BUNDLE_ID
  2. Wildcard App IDs: Here team id is used to match multiple apps with multiple bundle ids. This app id is used to match multiple apps. examples: TEAM_ID.BUNDLE_ID1, TEAM_ID.BUNDLE_ID2 …

89. Differences between internal testers and external testers in test-flight?

Answer:  Both internal and external testers will install your app from the TestFlight app. Once invited, they will be sent an email asking them to install the TestFlight app. Once they have done so, they’ll be able to install your beta app.
Internal Testers: Think of these users as employees who receive instant updates to your app without approval/review
  • Must be added manually via iTC
  • 25 Max allowed
  • Once your app is uploaded it’s available immediately for internal testers (before it has been reviewed)
  • All internal testers must be added as a user in your iTC “Users and Roles” settings, which gives them certain permissions (review other answers and the docs for this). You wouldn’t want to give just anyone permissions here.
  • Do not have a 60-day time limiti
External Testers
  • Will only be able to use your uploaded build for up to 60 days. If you add additional builds, they can update, and the 60 days starts over again.
  • Will be able to test your app after
    1. You have submitted it for review
    2. It gets approved in TestFlight review and
    3. You set it to be available for testing. The review process is usually instant for new builds with the same version number. If you add a new version number, the review process can take up to 48hrs as of 10/2016.
  • Up to 2000 email addresses can be added. Each email address will allow a user to install the app on multiple devices. The email addresses do not need to match their Apple IDs.
  • They receive an invite to install your app once your first build is available for testing. If you add a new user after making a build available for testing, they’ll immediately receive an invite. All users will receive notifications to install newer versions of the app if you upload additional builds.
  • Will be disallowed from using your app after you have pushed it to the official app store (which promptly ends the beta) or 60 days have passed since you started the beta, whichever comes first. If you end the beta without launching in the app store, and they try to open it, it will crash. Yay, Apple UX! If you do push a version to the app store with the same bundleName, version, and bundleID (build number doesn’t matter), then your beta testers will automatically receive the app-store version of the app when it goes live.

90. What is app thining?

Answer:  App thinning automatically detects the user’s device type (i.e. model name) and only downloads relevant content for the specific device. In other words, if you’re using an iPad Mini 1 (which does not have a retina display but rather a 1x resolution), then only your 1x files (more on this in a moment) will be downloaded.  The assets for more powerful and sharper iPads (such as the iPad Mini 3 or 4) will not be available for download).  Because the user needs only download the content that targets his/her specific device, this speeds up the download process and saves space on the device.

There are three aspects of app thining.

1. App Slicing : Slicing is the process of creating and delivering variants of the app bundle for different target devices. App Slicing delivers only relevant assets to each device (depending on screen resolution, architecture, etc.)  In fact, app slicing handles the majority of the app thinning process.
When you’re ready to submit the app, you upload the .IPA or .App file to iTunes Connect, as you typically would (but must use Xcode 7 as it contains the iOS 9 SDK with support for app thinning). The App Store then slices the app, creating specific variants that are distributed to each device depending on its capabilities.

2. On Demand Resources : On demand resources are files that can be downloaded after the app’s first installation.  For example, specific levels of a game (and these levels’ associated content) could be downloaded only when the player has unlocked them.  Further, earlier levels that the player has not engaged with after a certain set time can be removed to save storage on the device.
Enabling on demand resources involves changing the “Enable On Demand Resources” boolean to “Yes” in Xcode settings (under Build Settings).

3.  Bitcode : Bitcode makes apps as fast and efficient as possible on whatever device they’re running.  Bitcode automatically compiles the app for the most recent compiler and optimizes it for specific architectures. Can be turned on by the project settings under Build Settings and selecting bitcode to YES.

App thining process can be test by TestFlight software and install in various device. Size may be vary.


91. How to call segue programmatic?


For segue first, We have to set identifier in Class Inspector right side in XCode. Through that identifier, we can call like performSegue(withIdentifier: “identifier”, sender: nil) 

92. Diff between get and post?

93. Diff and use of  nsurlconnection and nsurlsession?

Answer: The URLSession class and related classes provide an API for downloading data from and uploading data to endpoints indicated by URLs. Your app can also use this API to perform background downloads when your app isn’t running or, in iOS, while your app is suspended.

An NSURLConnection object handles a single request and any follow-on requests. An NSURLSession object manages multiple tasks, each of which represents a single URL request and any follow-on requests. 

An NSURLConnection object lets you load the contents of a URL by providing a URL request object. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request

94. Understanding Session Task Types

Answer: There are three types of concrete session tasks:

  • URLSessionDataTask: Use this task for GET requests to retrieve data from servers to memory.
  • URLSessionUploadTask: Use this task to upload a file from disk to a web service via a POST or PUT method.
  • URLSessionDownloadTask: Use this task to download a file from a remote service to a temporary file location.

95. Background fetch 

Answer: to perform task when app is in background state.

first enable background fetch in capabilities.

tell iOS how often you want background fetch to happen. This is usually done inside the didFinishLaunchingWithOptions method in AppDelegate.swift, like this:

application.setMinimumBackgroundFetchInterval(1800) //or UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
performFetchWithCompletionHandler - use this method in appdelegate to perform required task

96. OOps concepts with real life and iOS examples // all concepts in detail

96. Type Of notification in iOS?


  1. Push / Remote notification
  2. Local notification
  3. Badge notification ( notification on Bell icon )

97. How Pushnotification works and what is limit for pushnotification?

Answer:  Pushnotification link

Answer : 1000 character and 4kb

98. Diff between i++ and ++i

Answer: i++ will increment the value of i, but return the original value of that i held before incremented

i = 1,  j = i++.  (result i = 2, j = 1) first assign then increment

++i will increment the value of i, and then return the incremented value

i = 1,  j = ++i.  (result i = 2, j = 2) first increment then assign

99. What is init? Different type of initialiser


Designated initializer

designated initializer is the primary initializer for a class. It must fully initialize all properties introduced by its class before calling a superclass initializer. A class can have more than one designated initializer.

Convenience initializer

convenience initializer is a secondary initializer that must call a designated initializer of the same class. It is useful when you want to provide default values or other custom setup. A class does not require convenience initializers

Final initializer

Swift gives us a final keyword just for this purpose: when you declare a class as being final, no other class can inherit from it. This means they can’t override your methods in order to change your behavior – they need to use your class the way it was written

Failable initializer

When talking about force unwrapping, I used this code:

let str = "5"
let num = Int(str)

That converts a string to an integer, but because you might try to pass any string there what you actually get back is an optional integer.

This is a failable initializer: an initializer that might work or might not. You can write these in your own structs and classes by using init?() rather than init(), and return nil if something goes wrong. The return value will then be an optional of your type, for you to unwrap however you want.

As an example, we could code a Person struct that must be created using a nine-letter ID string. If anything other than a nine-letter string is used we’ll return nil, otherwise we’ll continue as normal.

Here’s that in Swift:

struct Person {
    var id: String
    init?(id: String) {
        if id.count == 9 {
   = id
        } else {
            return nil

 Required initialiser 

Write the required modifier before the definition of a class initializer to indicate that every subclass of the class must implement that initializer.

You must also write the required modifier before every subclass implementation of a required initializer, to indicate that the initializer requirement applies to further subclasses in the chain. You do not write the override modifier when overriding a required designated initializer:

Consider the following example:

//required initclass 
classA {
 required init() {
    var a = 10

class classB: classA {
 required init() {
     var b = 30
let objA = classA()
let objB = classB()


The Swift initialization sequence has a little bit difference from Objective-C,

class BaseClass {
    var value : String
    init () {
        value = "hello"

the subclass below.

class SubClass : BaseClass {
    var subVar : String
    let subInt : Int
    override init() {
        subVar = "world"
        subInt = 2015
        value = "hello world 2015" // optional, change the value of superclass

The initialization sequence is:

  1. Initialize subclass’s var or let,
  2. Call super.init(), if the class has a super class,
  3. Change value of superclass, if you wanna do that.

100. Types of properties


There are two types of properties in Swift: stored properties and computed properties. Stored properties store values (constant or variable) as part of an instance or type, whereas computed properties don’t have a stored value.

Stored Properties

Stored properties of constants are defined by the ‘let’ keyword and Stored properties of variables are defined by the ‘var’ keyword.

  • During definition Stored property provides ‘default value’
  • During Initialization the user can initialize and modify the initial values
struct Number {
   var digits: Int
   let pi = 3.1415

var n = Number(digits: 12345)
n.digits = 67


Lazy stored property 

Swift provides a flexible property called ‘Lazy Stored Property’ where it won’t calculate the initial values when the variable is initialized for the first time. ‘lazy’ modifier is used before the variable declaration to have it as a lazy stored property.

Lazy Properties are used −

  • To delay object creation.
  • When the property is dependent on other parts of a class, that are not known yet
class sample {
   lazy var no = number()    // `var` declaration is required.

class number {
   var name = "Swift 4"

var firstsample = sample()

When we run the above program using playground, we get the following result −

Swift 4

Computed Properties

Rather than storing the values computed properties provide a getter and an optional setter to retrieve and set other properties and values indirectly.

class sample {
   var no1 = 0.0, no2 = 0.0
   var length = 300.0, breadth = 150.0

   var middle: (Double, Double) {
      get {
         return (length / 2, breadth / 2)
         no1 = axis.0 - (length / 2)
         no2 = axis.1 - (breadth / 2)

var result = sample()
result.middle = (0.0, 10.0)


When we run the above program using playground, we get the following result −

(150.0, 75.0)

When a computed property left the new value as undefined, the default value will be set for that particular variable.

101. What is type inference in Swift?

Answer: Swift is a type-safe language. … If you don’t specify the type of value you need, Swift uses type inference to work out the appropriate typeType inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide

102. Type Alias

Answer: type alias allows you to provide a new name for an existing data type into your program. … They simply provide a new name to an existing type. The main purpose of typealias is to make our code more readable, and clearer in context for human understanding.

103. How to create a typealias?

Answer:  It is declared using the keyword typealias as:

typealias name = existing type

In Swift, you can use typealias for most types. They can be either:

  • Built-in types ( String, Int)
  • User-defined types (for.e.g: class, struct, enum)
  • Complex types (for e.g: closures)

Typealias for built-in types

You can use typealias for all built in data Types as String, Int, Float etc.

For example:

typealias StudentName = String

The above declaration allows StudentName to be used everywhere instead of String. So, if you want to create a constant of type string but represents more like student name. You can do as:

let name:StudentName = "Jack"

Without using typealias, you should declare constant of type string as:

let name:String = "Jack"

Above both examples creates a constant of type String. But declaring with typealias, our code becomes more readable.

104. What is closure?

Answer: Closures are self-contained blocks of functionality that can be passed around and used in your code. (unnamed function)

ex. completion handler in alomofire

105. @nonescaping and @escaping closure

Answer:  closure parameters became @nonescaping by default, closure will also be execute with the function body, if wanna escape closure execution mark it as @escaping.

1. @nonescaping closures: (if you are getting value before scope end)

When passing a closure as the function argument, the closure gets execute with the function’s body and returns the compiler back. As the execution ends, the passed closure goes out of scope and have no more existence in memory.

Lifecycle of the @nonescaping closure:
1. Pass the closure as function argument, during the function call.
2. Do some additional work with function.
3. Function runs the closure.
4. Function returns the compiler back.

2. @escaping closures: (after scope end if scope is again executing after few seconds will have to use escaping )

When passing a closure as the function argument, the closure is being preserve to be execute later and function’s body gets executed, returns the compiler back. As the execution ends, the scope of the passed closure exist and have existence in memory, till the closure gets executed.
There are several ways to escaping the closure:

  • Storage: When you need to preserve the closure in storage that exist in the memory, past of the calling function get executed and return the compiler back. (Like waiting for the API response)
  • Asynchronous Execution: When you are executing the closure asynchronously on dispatch queue, the queue will hold the closure in memory for you, to be used in future. In this case you have no idea when the closure will get executed.

106. Sandbox

Answer:  sandbox is a set of fine-grained controls that limit the app’s access to files, preferences, network resources, hardware, and so on. As part of the sandboxing process, the system installs each app in its own sandbox directory, which acts as the home for the app and its data

107. Defer in swift

Answer:  A defer statement is used for executing code just before transferring program control outside of the scope that the statement appears in.

func updateImage() {
    defer { print("Did update image") }
    print("Will update image")
    imageView.image = updatedImage
// Will update Image
// Did update image

Order of execution with multiple defer statements

If multiple statements appear in the same scope, the order they appear is the reverse of the order they are executed (LIFO). The last defined statement is the first to be executed which is demonstrated by the following example by printing numbers in logical order.

func printStringNumbers() {
    defer { print("1") }
    defer { print("2") }
    defer { print("3") }
/// Prints 4, 3, 2, 1

108. Higher order function


Swift’s Array type has a few methods that are higher order functions: sorted, map, filter, and reduce.

Sorted : If we call sorted on an array it will return a new array that sorted in ascending order. like sorting of array of numbers

Map : Mapping is similar to sort in that it iterates through the array that is calling it, but instead of sorting it changes each element of the array based on the closure passed to the method. like changing array of numbers to arrays of strings.

let houseName:[String] = [“starks” ,”lanniesters” , “targaryens” ,”baratheon” , “arryn”]
let mappedHouseCount ={$0.count}
Characters count of each element in house name :- [6, 11, 10, 9, 5]

Filter: filter array according to condition like from array of numbers get array of numbers less that 5

Reduce : The reduce function allows you to combine all the elements in an array. like combine numbers of array and return as string.

let compactMapValue = place.compactMap{$0}
 // here the optionals are removed["winterfell", "highgarden", "Vale", "iron islands", "essos", "andalos"]

compactMap is also used to filter out the nil value

let arrayWithNil:[String?] = [“eleven” , nil , “demogorgon” , nil , “max” , nil , “lucus” , nil , “dustin”]
let filteredNilArray = arrayWithNil.compactMap{$0}
print(filterNilArray)print (“Array with nil = \(arrayWithNil.count) and with out nil count = \(filterNilArray.count)”)

the printed values are

[“eleven”, “demogorgon”, “max”, “lucus”, “dustin”]
Array with nil = 9 and with out nil count = 5

109. Diff. between flat and flatmap

Answer:  So map transforms an array of values into an array of other values, and flatMap does the same thing, but also flattens a result of nested collections into just a single array.

let scoreByName = ["henry":[0,5,8], "John":[2,5,8]]
let mapped = {$0.value}
print(mapped) // [[0,5,8], [2,5,8]] - array of array

let flatMapped = scoreByName.flatmap {$0.value}
//[0,5,8,2,5,8] - flattened to only an array

110. What is codable?

Answer:  Codable: a protocol specifically for archiving and unarchiving data, which is a fancy way of saying “converting objects into plain text and back again.”

111. What is JSONEncoder

Answer: This part of the process is powered by a new type called JSONEncoder. Its job is to take something that conforms to Codable and send back that object in JavaScript Object Notation (JSON) – the name implies it’s specific to JavaScript, but in practice we all use it because it’s so fast and simple.

112. What is stack and heap?


113. What is the difference between aspect fill and aspect fit when displaying an image?

Answer: Aspect fit ensures all parts of the image are visible, whereas aspect fill may crop the image to ensure it takes up all available space.

114. What steps do you follow to identify and resolve crashes?

Answer : by using Assert, Precondition and Fatal Error in Swift


what is “some” in SwiftUI?

var body: some View defines a new computed property called body, which has an interesting type: some View. This means it will return something that conforms to the View protocol, but that extra some keyword adds an important restriction: it must always be the same kind of view being returned – you can’t sometimes return one type of thing and other times return a different type of thing.

We’ll look at this feature more shortly, but for now just remember that it means “one specific sort of view must be sent back from this property.”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s