Top IOS Interview Questions and Answers (Sept 2018) Part 4

Q1. Array — allocate 10 element but os allocate memory space after that to other array, so how will next element insert ? At what location…

Top IOS Interview Questions and Answers (Sept 2018) Part 4

Q1. Array — allocate 10 element but os allocate memory space after that to other array, so how will next element insert ? At what location?
How does Swift manage Arrays internally?

Solution: Arrays created in Swift hold their values in a contiguous region of memory. For this reason, you can efficiently pass a Swift array into a C API that requires that kind of structure.

As you mention, an array can grow as you append values to it, and at certain points that means that a fresh, larger, region of memory is allocated, and the previous values are copied into it. It is for this reason that its stated that operations like append may be O(n) – that is, the worst-case time to perform an append operation grows in proportion to the current size of the array (because of the time taken to copy the values over).

However, when the array has to grow its storage, the amount of new storage it allocates each time grows exponentially, which means that reallocations become rarer and rarer as you append, which means the “amortized” time to append over all calls approaches constant time.

Arrays also have a method, reserveCapacity, that allows you to preemptively avoid reallocations on calling append by requesting the array allocate itself some minimum amount of space up front. You can use this if you know ahead of time how many values you plan to hold in the array.

Inserting a new value into the middle of an array is also O(n), because arrays are held in contiguous memory, so inserting a new value involves shuffling subsequent values along to the end. Unlike appending though, this does not improve over multiple calls. This is very different from, say, a linked list where you can insert in O(1) i.e. constant time. But bear in mind the big tradeoff is that arrays are also randomly accessible in constant time, unlike linked lists.

Changes to single values in the array in-place (i.e. assigning via a subscript) should be O(1)(subscript doesn't actually have a documenting comment but this is a pretty safe bet). This means if you create an array, populate it, and then don't append or insert into it, it should behave similarly to a Java array in terms of performance.

There’s one caveat to all this — arrays have “value” semantics. This means if you have an array variable a, and you assign it to another array variable b, this is essentially copying the array. Subsequent changes to the values in a will not affect b, and changing b will not affect a. This is unlike "reference" semantics where both a and b point to the same array and any changes made to it via a would be reflected to someone looking at it via b.

However, Swift arrays are actually “Copy-on-Write”. That is, when you assign a to b no copying actually takes place. It only happens when one of the two variables is changed ("mutated"). This brings a big performance benefit, but it does mean that if two arrays are referencing the same storage because neither has performed a write since the copy, a change like a subscript assign does have a one-off cost of duplicating the entire array at that point.

Q2. What are “mutable” and “immutable” objects?

Solution: In a certain way, “mutable” and “immutable” only make sense when talking about reference types. If you try to extend it to value types, then all value types can be considered functionally equivalent to “immutable” reference types.

For example, consider a var of type Int. Is this mutable? Some of you might say, sure -- you can change its visible "value" by assigning (=) to it. However, the same can be said of a var of NSNumber and NSString -- you can change its visible value by assigning to it. But NSNumber and NSString are described as immutable classes.

What is really happening for reference types is that assigning to them causes the variable (a pointer) to point to a new object. Neither the old nor new object itself is “changed”, but since it points to a different object, you “see” a new value.

What we mean when we say a class is “mutable” is that it offers an API (method or reference) to actually change the contents of the object. But how do we know that the object has changed? (rather it being a new object?) It’s because we could have another reference to the same object, and changes to the object through one reference is visible through another reference. But these properties (pointing to different objects, having multiple pointers to the same object) inherently only apply to reference types. Value types, by definition, cannot have such “sharing” (unless part of the “value” is a reference type, like in Array), and thus, the consequence of "mutability" cannot happen for value types.

So if you make an immutable class that wraps an integer, it would be operationally equivalent to an Int -- in both cases, the only way to change a variable's value would be to assign (=) to it. So Int should also similarly be considered "immutable".

Q3. What are the possible ways to communicate with classes?

Solution:
– Protocols
– NSNotificationCenter
– Key-Value Observation (KVO)
– Delegates
– Blocks
– Target-Action

Q4. Why viewControllers required?

Solution: A view controller is not drawable to the screen directly, it manages a group of view objects. View controllers usually have a single view with many subviews. The view controller manages the state of these views. A view controller is smart, and has knowledge of your application’s inner workings. It tells the dumb view objects what to do and how to show themselves.

A view controller is the glue between your overall application and the screen. It controls the views that it owns according to the logic of your application.

In short its role is -

  1. View Management
  2. Data Marshaling
  3. User Interactions
  4. Resource Management
  5. Adaptivity

Q5. Suppose I have 10 cells in a table view — 6 are visible — How much memory it will take (assume x memory takes 1 cell), How tableview works?

Solution: dequeueReusableCellWithIdentifier. Instead of creating every single cell and then selectively displaying them, we only create a handful of cells, enough to fill the screen and a little more. As we scroll, we reuse the cells offscreen, leading to a much more memory efficient task.

Assuming half part of upper and half part of lower cell — it will contain 8 Cells to reuse , so it will take 8x.

Q6. I have a application which runs animation in it, which thread it will be using? How do you manage multiple animations in a single screen?

Solution:

  1. Starting Animations Using the Block-Based Methods

The specified animations are started immediately on another thread so as to avoid blocking the current thread or your application’s main thread.

2. Starting Animations Using the Begin/Commit Methods

Execution of the animations occurs on a secondary thread so as to avoid blocking the current thread or your application’s main thread.

Q7. Difference between NSCoding and Codable?

Solution: To support encoding and decoding of instances in iOS, a class must adopt the NSCoding protocol and implement its methods:

  1. init(coder:) — Returns an object initialized from data in a given unarchiver.
  2. encode(with:) — Encodes the receiver using a given archiver.

init(coder:) and encode(with:) must contain the code for each property that needs to be encoded or decoded.

Codable : Make your data types encodable and decodable for compatibility with external representations such as JSON. It provides support for class, struct and enum as well.

typealias Codable = Decodable & Encodable

Limitations 🚫

  1. For now you cannot conform to Codable in an extension
  2. You must use a concrete type to encode and decode.

Hope these questions will help you.

References:

  1. https://stackoverflow.com/questions/27943629/how-does-swift-manage-arrays-internally
  2. https://stackoverflow.com/questions/24221786/are-swift-mutable-strings-really-mutable-or-are-they-just-like-java-strings
  3. https://www.objc.io/issues/7-foundation/communication-patterns/
  4. https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/
  5. https://stackoverflow.com/questions/31814563/whats-the-difference-between-a-view-and-a-viewcontroller
  6. https://developer.apple.com/library/archive/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/AnimatingViews/AnimatingViews.html
  7. https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
  8. https://hackernoon.com/everything-about-codable-in-swift-4-97d0e18a2999