Top IOS Interview Questions and Answers (Jan 2019) Part 3

iOS interview questions 2019

Top IOS Interview Questions and Answers (Jan 2019) Part 3

iOS interview questions 2019

This article includes more questions from VMware for IOS position. Hope it will help you.

Q1. In which application have you used and why — MVVM , MVC ?

Ans: MVVM

First off, the key benefit is enabling true separation between the view and model. What that means in real terms is that if/when your model needs to change, it can without the view needing to and vice-versa.

Secondly, while your model may contain all the data you might need in your view, you may want to abstract that data in such a way that your model doesn't support. For example, say your model contains a date property. In the model it can exist solely as a DateTime object but your view might want to present it in a completely different way. Without the viewmodel you'd either have to duplicate the property in the model to support the view or modify the property which could seriously obfuscate the 'model'.

You can also use a viewmodel to aggregate parts of your model that exist in separate classes/libraries to facilitate a more fluent interface for the view to deal with. It's very unlikely that you'll want to work with data in your code in the same way that a user will want to or will want that data presented to them.

On top of that, you get support for automatic two-way data binding between the view and viewmodel.

What motivates MVC

At the heart of MVC is what I call Separated Presentation. The idea behind Separated Presentation is to make a clear division between domain objects that model our perception of the real world, and presentation objects that are the GUI elements we see on the screen. Domain objects should be completely self contained and work without reference to the presentation, they should also be able to support multiple presentations, possibly simultaneously.

Q2. Why we perform UI Operation on Main thread?

Ans: You have to update your UI on the main thread for a few reasons.

The first one is that, in Cocoa Touch, the UIApplication gets set up on the main thread. It’s the first part of your app that gets instantiated when you start your app.

All views on screen, such as a label you’re working with, are descendants of this UIApplication instance. So, when you tap a button or work with a button, these must be updated on the main thread because they’re part of the main thread. Likewise, any events originating from a button or label, like a tap or pinch, will be part of the main thread and should be handled there.

Another reason is graphics rendering: the graphics pipeline of the iPhone is ultimately synchronous.

Let’s say you’re working with a UILabel, a bit of text on screen. You wait for an asynchronous request to come back in, perhaps the user data that contains the username of the iPhone user. Once the data comes in, you update the label with the username.

UIKit, the framework that UILabel is part of, then renders the text on screen. It’ll rasterize the font — because fonts are vectors — and turn the text into pixels. When that text is part of a blended layer, for instance when clipping it, or applying transparency, the graphics renderer calculates which pixel of the label it should show. These pixels are then put together with the rest of the screen, up to 60 times per second.

Drawing onto the iPhone screen — lighting up pixels on the LED display — is a process that needs to happen at once, all pixels on the screen at the same time. Asynchronous programming is by definition not synchronous, but parallel, and you can’t be certain when an asynchronous operation finishes.

If you would allow asynchronous drawing to the iPhone display, you could end up with a whole lot of flickers and missing parts because the processing for that part wasn’t ready when the entire screen is rendered.

Ultimately, it’s simply easier to update UI on the main thread. It’ll save you a whole lot of decisions, issues that need solving, and bugs. You can of course create part of your UI on an asynchronous thread, as long as the updating of the UI is synchronous.

A few examples:

  • Applying filters or graphics effects to a view, like rounding corners or working with CIFilter. These processes are so intensive you’ll want to cache them, and dispatch them on an async thread before drawing them to the screen.
  • Creating dynamic graphics, such as animations. You’d process them first, then play back the processed animation. The same goes for drawing graphs and generated images.
  • Downloading a network resource, like user data, and then updating the UI synchronously.

Exceptions exist of course, and most notably the AsyncDisplayKit for iOS from Facebook. As an integral part of the framework views are rendered asynchronously, although that doesn’t mean the iPhone display is updated asynchronously. In any case, the framework allows for buttery smooth UIs!

This is a cool video from WWDC showing you how to render UI concurrently: Building Concurrent User Interfaces on iOS

Q3. Whats new in iOS 12 and APNS?

Q4. When to use Initialize vs Load API of NSObject?

Ans:

load() : Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.

  1. Invoked whenever a class or category is added to the Objective-C runtime. When your app starts
  2. Called even if you don’t invoke any methods of a class.
  3. Invoked once per class and once per a class category, if +load is implemented in a category
  4. Framework classes are loaded at this time
  5. C++ static initializers are not loaded
  6. Invoked before main method.
  7. It’s safe to use autorelease object here because ARC create autorelease pool automatically.

initialize() : Initializes the class before it receives its first message.

  1. Called once per a class
  2. Won’t be not called if you don’t invoke a class.
  3. +initialize method could be invoked more than once.
    Example it will be called twice if a subclass don’t implement initialize
  4. Is called when you first time call a class
  5. Called in thread safe manner
  6. Superclasses receive initialize message before their subclasses

Q5. What is APNS steps to add in your application?

Ans: Setting Up APNS for Push Notifications.

Step 1: Create an App ID.

Step 2: Create an APNs SSL Certificate.

Step 3: Register a Test Device.

Step 4: Create an iOS Distribution Certificate.

Step 5: Create a Provisioning Profile.

Step 6: project set-up, enabling APNs, In Xcode, go to your Targets, under your app’s name, select Capabilities and find Push Notifications in the list, switch toON

Step 7: Add UserNotifications framework in AppDelegate, start requestAuthorization and then registerForRemoteNotifications.

Step 8: Two api’s given by App delegate, one gets us the device token, the other one checks for errors if any

didRegisterForRemoteNotificationsWithDeviceToken & didFailToRegisterForRemoteNotificationsWithError

Step 9: Share the token with your server using rest api and start receiving push notifications.

Q6. Iterative vs Recursive approach — Which is faster and why?

Ans: Technically, iterative loops fit typical computer systems better at the hardware level: at the machine code level, a loop is just a test and a conditional jump, whereas recursion (implemented naively) involves pushing a stack frame, jumping, returning, and popping back from the stack.

  1. Recursion is always applied to method whereas, iteration is applied to set of instruction.
  2. Recursion can be faster than iteration. Now that multi-core chips are the norm, performance can be improved by distributing the load across the cores. However this is not done in iterative solutions as it is a difficult, and sometimes impossible, optimization to perform. But languages that rely on stateless idempotent methods cannot perform iteration, so the programmer must use recursion. The fact that the methods are stateless and idempotent means that the optimizer can always distribute the load across multiple cores, improving performance.

Q7. Which one we should use ≥ vs < operator?

Ans: ≥ need to check condition (c1 & c2) while in case of < only one condition need to check.

Q8. KVC vs KVO ?

Ans: Key-Value-Coding (KVC) means accessing a property or value using a string.

id someValue = [myObject valueForKeyPath:@"foo.bar.baz"];

Which could be the same as:

id someValue = [[[myObject foo] bar] baz];

Key-Value-Observing (KVO) allows you to observe changes to a property or value.

To observe a property using KVO you would identify to property with a string; i.e., using KVC. Therefore, the observable object must be KVC compliant.

[myObject addObserver:self forKeyPath:@"foo.bar.baz" options:0 context:NULL];

Q9. What is autorelease, autorelease pool , How many autorelease pool is there?

Ans: In a reference-counted environment (as opposed to one which uses garbage collection), an NSAutoreleasePool object contains objects that have received an autorelease message and when drained it sends a release message to each of those objects. Thus, sending autorelease instead of release to an object extends the lifetime of that object at least until the pool itself is drained (it may be longer if the object is subsequently retained). An object can be put into the same pool several times, in which case it receives a release message for each time it was put into the pool.

The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event. If you use the Application Kit, you therefore typically don’t have to create your own pools. If your application creates a lot of temporary autoreleased objects within the event loop, however, it may be beneficial to create “local” autorelease pools to help to minimize the peak memory footprint.

Q10. How ARC works?

Ans: Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. This memory holds information about the type of the instance, together with the values of any stored properties associated with that instance.

Additionally, when an instance is no longer needed, ARC frees up the memory used by that instance so that the memory can be used for other purposes instead. This ensures that class instances do not take up space in memory when they are no longer needed.

However, if ARC were to deallocate an instance that was still in use, it would no longer be possible to access that instance’s properties, or call that instance’s methods. Indeed, if you tried to access the instance, your app would most likely crash.

To make sure that instances don’t disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.

To make this possible, whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes a strong reference to the instance. The reference is called a “strong” reference because it keeps a firm hold on that instance, and does not allow it to be deallocated for as long as that strong reference remains.

Q11. Have you used Operation and OperationQueue? Where? what are the overridden api for Operation Class?

Ans: Because the Operation class is an abstract class, you do not use it directly but instead subclass or use one of the system-defined subclasses (NSInvocationOperation or BlockOperation) to perform the actual task.

Methods to Override

For non-concurrent operations, you typically override only one method:

If you are creating a concurrent operation, you need to override the following methods and properties at a minimum:

In a concurrent operation, your start() method is responsible for starting the operation in an asynchronous manner.Upon starting the operation, your start() method should also update the execution state of the operation as reported by the isExecuting property. You do this by sending out KVO notifications for the isExecuting key path, which lets interested clients know that the operation is now running. Your isExecuting property must also provide the status in a thread-safe manner.

Upon completion or cancellation of its task, your concurrent operation object must generate KVO notifications for both the isExecuting and isFinished key paths to mark the final change of state for your operation.

Source: https://developer.apple.com/documentation/foundation/operation

Q12. Why we use ManageObjectContext, Whats it purpose?

Ans: NSManagedObjectContext : An object representing a single object space or scratch pad that you use to fetch, create, and save managed objects.

  • The context is a powerful object with a central role in the life cycle of managed objects, with responsibilities from life cycle management (including faulting) to validation, inverse relationship handling, and undo/redo.
  • Managed object contexts have a parent store from which they retrieve data representing managed objects and through which they commit changes to managed objects.
    Prior to OS X v10.7 and iOS v5.0, the parent store is always a persistent store coordinator. In macOS 10.7 and later and iOS v5.0 and later, the parent store may be another managed object context.
  • A context posts notifications at various points see NSManagedObjectContextObjectsDidChange
  • Concurrency: When you create a managed object context using init(concurrencyType:), you have two options for its thread (queue) association
    1. Private queue (NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType): The context creates and manages a private queue.
    2. Main queue (NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType): The context is associated with the main queue, and as such is tied into the application’s event loop, but it is otherwise similar to a private queue-based context. You use this queue type for contexts linked to controllers and UI objects that are required to be used only on the main thread.

Source: https://developer.apple.com/documentation/coredata/nsmanagedobjectcontext

Bonus Time: DS Questions

  1. Sum each digit until it converts into a single digit?
  2. Given root node and a ptr to a node which need to delete, Write code for deleting a node for which ptr is given?

If you have any comment, question, or recommendation, feel free to post them in the comment section below! You can also follow me on Medium for new articles and connect with me on LinkedIn.

References:

  1. https://softwareengineering.stackexchange.com/questions/105352/why-should-i-use-an-mvc-pattern
  2. https://stackoverflow.com/questions/1644453/why-mvvm-and-what-are-its-core-benefits
  3. https://www.quora.com/Why-must-the-UI-always-be-updated-on-Main-Thread
  4. https://developer.apple.com/documentation/objectivec/nsobject/1418815-load
  5. https://medium.com/@kostiakoval/load-vs-initialize-a1b3dc7ad6eb
  6. https://developer.apple.com/documentation/objectivec/nsobject/1418639-initialize
  7. https://www.quora.com/Is-recursion-faster-than-loops
  8. https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH
  9. https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html