Thursday, 11 March 2021

IOS Interview Question

 1.What is the difference between a UIAlertView and a UIAlertController?

Ans: The UIAlertView class has a simple interface and is used to present modal alerts. Apple has deprecated UIAlertView in iOS 8 though. As of iOS 8, it is recommended to use the UIAlertController class to present action sheets and modal alerts.

2. Can you explain MVC, and how it's used on Apple's platforms?

Ans: MVC – short for Model-View-Controller – is Apple's preferred way of architecting apps for its platforms, and so it's the default approach used by most developers on Apple platforms. In MVC each piece of your code is one of three things: Models store your data, such as the names of products in a store

3. What is the difference between an extension and a protocol extension?

Ans: Protocols let you describe what methods something should have, but don't provide the code inside. Extensions let you provide the code inside your methods, but only affect one data type – you can't add the method to lots of types at the same time.

4. What problem does optional chaining solve?

Ans: The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null . For example, consider an object obj which has a nested structure.

5. What is the purpose of NotificationCenter?

Ans: It helps for observation and broadcasting singles from one class to multiple classes. Post singles from one class to multiple classes. Receiving singles from multiple classes.

6. What is the purpose of IBDesignable?

Ans:. When applied to a UIView or NSView subclass, the @IBDesignable designation lets Interface Builder know that it should render the view directly in the canvas. This allows seeing how your custom views will appear without building and running your app after each change

7. What is an efficient way to cache data in memory?

Ans:. There are lots of ways of making caches, but NSCache is definitely preferable because it gets cleared by the system when memory is low.

8. What are property observers?

Ans:-Property Observers. Property observers observe and respond to changes in a property's value. Property observers are called every time a property's value is set, even if the new value is the same as the property's current value. You can add property observers in the following places: Stored properties that you define.

9. How much experience do you have using Core Image? Can you give examples?

Ans:- Some developers confuse Core Graphics and Core Image, which is a mistake – they are quite different. Core Image is less used, but is helpful for filtering images: blurring or sharpening, adjusting colors, and so on

10. What are the main differences between classes and structs in Swift?

Ans:  In Swift, structs are value types whereas classes are reference types. When you copy a struct, you end up with two unique copies of the data. When you copy a class, you end up with two references to one instance of the data. It's a crucial difference, and it affects your choice between classes or structs.

11. What is a variadic function?

Ans:- Variadic functions accept any number of parameters. Swift writes them using ..., and we’re handed the parameters as an array. Again, try to give an example – something like print() is a good place to start.

12. what is p12 certificate

Ans:.p12 is an alternate extension for what is generally referred to as a "PFX file", it's the combined format that holds the private key and certificate and is the format most modern signing utilities use. If you have a . p12 file that you exported from Firefox or Safari just rename the . p12 extension to

13. what is typealias in swift

Ans:- Swift Typealias is used to provide a new name for an existing data type in the program. Once you create a typealias, you can use the aliased name instead of the exsisting name throughout the program. Typealias doesn't create a new data type, it simply provides a new name to the existing data type.

14. What is the purpose of UIMenuController?

Ans: UIMenuController class is used to display an editing menu over the UI element. The editing menu is a rectangular box with different actions. By default, there are some inbuilt actions such as cut, copy, paste, lookup, replace, define etc.

15. What is UserDefaults good for? What is UserDefaults not good for?

Ans:- This should immediately have you thinking about speed, size, and security: UserDefaults is bad at large amounts of data because it slows your app load, it’s annoying for complex data types because of NSCoding, and a bad choice for information such as credit cards and passwords – recommend the keychain instead.

16. What is PLIST in iOS?

Ans:- PLIST stands for Property List. PLIST is basically a dictionary of value and keys that can be stored in our file system with a .plist file extension. The property list is used as a portable and lightweight means to store a lesser amount of data. They are normally written in XML.

17. What is a dictionary?

Ans: Dictionaries are an association of an unordered collection of key-value pairs. Each value is associated with a unique key, which is a hashable type such as a number or string. We can use the dictionary concept in swift programming language whenever we want to obtain the values based on a key value.

18. What is a Protocol in swift?

Ans: The protocol is a very common feature of the Swift programming language and the protocol is a concept that is similar to an interface from java. A protocol defines a blueprint of properties, methods, and other requirements that are suitable for a particular task.

In its simplest form, the protocol is an interface that describes some methods and properties. The protocol is just described as the properties or methods skeleton instead of implementation. Properties and methods implementation can be done by defining enumerations, functions, and classes.

Protocols are declared after the structure, enumeration or class type names. A single and multiple protocol declaration can be possible. Multiple protocols are separated by commas.

19. What is the use of double question mark “??” in swift?

Ans:- The double question mark “??” is a nil-coalescing operator, it is mainly a shorthand for the ternary conditional operator where we used to test for nil. A double question mark is also used to provide a default value for a variable.  stringVar ?? “default string”  This exactly does the common thing, if stringVar is not nil then it is returned, otherwise the “default string” is returned.

20. What is a GUARD statement? What is the benefit of using the GUARD statement in swift?

Ans:- A GUARD statement is used to transfer the program control out of the scope when one or more conditions are not met. Using this statement helps in avoiding the pyramid of doom.

21. What is the difference between Array and NSArray?

Ans: The difference between Array and NSArray are given below:  

An array can hold only one type of data, whereas NSArray can hold different types of data. 

An array is a value type, whereas NSArray is an immutable reference type.       

22. What is the difference between class and structure?

Ans: The difference between class and structure are given below:  

Classes are reference types, whereas structs are value types. 

Classes can be built on other classes, whereas struct cannot inherit from another struct. 

Classes have an inheritance, whereas structs cannot have an inheritance. 

In class, we can create an instance with “let” keywords and attempt to mutate its property, whereas there is no Mutability in Structs. 

Classes have Type Casting, whereas struct doesn’t have Type Casting.

23. How to pass the data between view controllers?

Ans: There are three ways to pass the data between view controllers as shown below.  

Using Segue, in prepareForSegue method (Forward). 

Setting the variable directly (Backword). 

Using Delegate (Backword).

24. What are the different ways to pass data in swift?

Ans: - There are several ways to pass data in swift such as KVO, Delegate, NSNotification & Callbacks, Target-Action, etc.

25. Explain the usage of Class and benefits of Inheritance.

Ans:- They are:

 Reuse implementation Subclass provides dynamic dispatch. 

Subclass provides the reuse interface.

 Modularity 

Overriding provides the mechanism for customization.

26. Explain some Common features of Protocols & Superclasses.

Ans: Some common features of Protocol & Superclass are given below: 

Interface reuse. 

Implementation reuse. 

Supporting modular design. 

Provides points for customization.

27. Explain some biggest changes in UserNotifications.

Ans: Some bigger changes in UserNotifications are given below: 

Allows adding images, audio, and videos. 

Allows creating custom interfaces for notifications. 

Allows managing the notifications with interface in the notification center.

28. What are the Higher-Order functions in swift?

Ans:- The higher-order functions are given below: 

Map: Transform the array contents. 

Reduce: Reduce the values in the collection to a single value. 

Sort: Sorting the arrays. 

Filter: Transform the array contents.

30. What are the various ways to unwrap an optional in swift?

Ans:-There are seven ways to unwrap an optional in swift. They are: 

Guard statement: safe. 

Forced unwrapping: using “!” operator, unsafe.

 Optional binding: safe. Optional pattern: safe. 

Nil coalescing operator: safe. 

Implicitly unwrapped variable declaration: unsafe in many cases. 

Optional chaining: safe.

31. What mechanism does iOS support for multi-threading?

Ans: They are: 

NSThread: It can create a low-level thread which can be started by using the “start” method. NSOperationQueue: It allows a pool of threads to be created and is used to execute “NSOperations” in parallel.

32. What is Swift module?

Ans: 

  • A module is a single unit of code distribution.
  • A framework or application is built and shipped as a single unit and that can be imported by another module using the swift import keyword.
  • Each build target in the Xcode tool is treated as a separate module in swift.

33.When would you use the guard keyword in Swift?
Ans: A guard statement is used to transfer program control out of a scope if one or more conditions aren't met. A guard statement has the following form: guard condition else { statements.

34. What is the difference between try, try?, and try! in Swift?
Ans: A regular try requires you to catch errors, try? converts the throwing call into an optional where you’ll get back nil on failure, and try! will cause your app to crash if the throwing call fails. All three have their uses!

35. What is the function of anchors in Auto Layout?
Ans: Auto Layout anchors make it easy to position your views relative to others. There are lots of anchors to choose from: leading and trailing edges, top and bottom edges, center X and center Y, and more.

36. When would you use the defer keyword in Swift?
Ans: This is used to delay a piece of work until a method ends. Try to give a specific example, such as saving a file once everything has been written.

37. How does CloudKit differ from Core Data?
Ans: Core Data on its own, is completely local and does not automatically work with any of Apple's cloud services. Core Data with iCloud enabled turns on syncing via iCloud. ... CloudKit does not store data on the device, so the data is not available if the device is offline.

38. What is the difference between aspect fill and aspect fit when displaying an image?
Ans: 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.

39. What are tuples and why are they useful?
Ans: Tuples are a bit like anonymous structs, and are helpful for returning multiple values from a method in a type-safe way, among other things.

40. What is the difference between weak and unowned?
Ans. “Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization.”

41. What does the #available syntax do?
Ans: This syntax was introduced in Swift 2.0 to allow run-time version checking of features by OS version number. It allows you to target an older version of iOS while selectively limiting features available only in newer iOS versions.

1- How could you set up Live Rendering?
The attribute @IBDesignable lets Interface Builder perform live updates on a particular view. IBDesignable requires Init frame to be defined as well in UIView class.

2- What is the difference between Synchronous & Asynchronous task?
Synchronous: waits until the task have completed Asynchronous: completes a task in the background and can notify you when complete

3- Explain Compilation Conditions
Compilation Conditions to use if DEBUG … endif structure to include or disable given block of code ve separate targets.

4- What is made up of NSError object?
There are three parts of NSError object a domain, an error code, and a user info dictionary. The domain is a string that identifies what categories of errors this error is coming from.

6- What is the bounding box?
The bounding box is a term used in geometry; it refers to the smallest measure (area or volume) within which a given set of points.

7- Why don’t we use strong for enum property in Objective-C?
Because enums aren’t objects, so we don’t specify strong or weak here.

8- What is @synthesize in Objective-C?
synthesize generates getter and setter methods for your property.

9- What is @dynamic in Objective-C?
We use dynamic for subclasses of NSManagedObject. @dynamic tells the compiler that getter and setters are implemented somewhere else.

10- Why do we use synchronized?
synchronized guarantees that only one thread can be executing that code in the block at any given time.

11- What is the difference strong, weaks, read only and copy?

strongweakassign property attributes define how memory for that property will be managed.

Strong means that the reference count will be increased and
the reference to it will be maintained through the life of the object

Weak ( non-strong reference ), 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.

  • Every time used on var
  • Every time used on an optional type
  • Automatically changes itself to nil

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.

for more details check this out

12- What is Dynamic Dispatch?
Dynamic Dispatch is the process of selecting which implementation
of a polymorphic operation that’s a method or a function to call at run time. This means, that when we wanna invoke our methods like object method. but Swift does not default to dynamic dispatch

13- What’s Code Coverage?
Code coverage is a metric that helps us to measure the value of our unit tests.

14- What’s Completion Handler?
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.

15- How to Prioritize Usability in Design ?
Broke down its design process to prioritize usability in 4 steps:

  • Think like the user, then design the UX.
  • Remember that users are people, not demographics.
  • When promoting an app, consider all the situations in which it could be useful.
  • Keep working on the utility of the app even after launch.

16- What’s the difference between the frame and the bounds?
The bounds of a UIView is the rectangle, expressed as a location (x,y) and size (width, height) relative to its own coordinate system (0,0).
The frame of a UIView is the rectangle, expressed as a location (x,y) and size (width, height) relative to the superview it is contained within.

17- What is Responder Chain ?
A ResponderChain is a hierarchy of objects that have the opportunity to respond to events received.

18- What is Regular expressions?
Regular expressions are special string patterns that describe how to search through a string.

19- What is Operator Overloading?
Operator overloading allows us to change how existing operators behave with types that both already exist. Operators are those little symbols like +*, and /

20- What is TVMLKit?
TVMLKit is the glue between TVML, JavaScript, and your native tvOS application.

21- What is Platform limitations of tvOS?
First
, tvOS provides no browser support of any kind, nor is there any WebKit or other web-based rendering engine you can program against. This means your app can’t link out to a web browser for anything, including web links, OAuth, or social media sites.

Second, tvOS apps cannot explicitly use local storage. At product launch, the devices ship with either 32 GB or 64 GB of hard drive space, but apps are not permitted to write directly to the onboard storage.

tvOS app bundle cannot exceed 4 GB.

22- What is Functions?
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.

23- What is ABI?
ABIs are important when it comes to applications that use external libraries. If a program is built to use a particular library and that library is later updated, you don’t want to have to re-compile that application (and from the end user's standpoint, you may not have the source). If the updated library uses the same ABI, then your program will not need to change. ABI stability will come with Swift 5.0

            

24- Why is design pattern very important ?
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

25- What is Singleton Pattern ?
The Singleton design pattern ensures that only one instance exists for a given class and that there’s a global access point to that instance. It usually uses lazy loading to create the single instance when it’s needed the first time.

26- What is Facade Design Pattern?
The Facade design pattern provides a single interface to a complex subsystem. Instead of exposing the user to a set of classes and their APIs, you only expose one simple unified API.

27- What is Decorator Design Pattern?
The Decorator pattern dynamically adds behaviors and responsibilities to an object without modifying its code. It’s an alternative to subclassing where you modify a class’s behavior by wrapping it with another object.

In Objective-C there are two very common implementations of this pattern: Category and Delegation. In Swift there are also two very common implementations of this pattern: Extensions and Delegation.

28- What is Adapter Pattern?
An Adapter allows classes with incompatible interfaces to work together. It wraps itself around an object and exposes a standard interface to interact with that object.

29- What is Observer Pattern?
In the Observer pattern, one object notifies other objects of any state changes.

Cocoa implements the observer pattern in two ways: Notifications and Key-Value Observing (KVO).

30- What is Memento Pattern?
In Memento Pattern saves your stuff somewhere. Later on, this externalized state can be restored without violating encapsulation; that is, private data remains private. One of Apple’s specialized implementations of the Memento pattern is Archiving other hand iOS uses the Memento pattern as part of State Restoration.

31- Explain MVC

  • Models — responsible for the domain data or a data access layer which manipulates the data, think of ‘Person’ or ‘PersonDataProvider’ classes.
  • Views — responsible for the presentation layer (GUI), for iOS environment think of everything starting with ‘UI’ prefix.
  • Controller/Presenter/ViewModel — the glue or the mediator between the Model and the View, in general responsible for altering the Model by reacting to the user’s actions performed on the View and updating the View with changes from the Model.

32- Explain MVVM
UIKit independent representation of your View and its state. The View Model invokes changes in the Model and updates itself with the updated Model, and since we have a binding between the View and the View Model, the first is updated accordingly.

Your view model will actually take in your model, and it can format the information that’s going to be displayed on your view.

There is a more known framework called RxSwift. It contains RxCocoa, which are reactive extensions for Cocoa and CocoaTouch.

33- How many different annotations available in Objective-C ?

  • _Null_unspecified, which bridges to a Swift implicitly unwrapped optional. This is the default.
  • _Nonnull, the value won’t be nil it bridges to a regular reference.
  • _Nullable the value can be nil, it bridges to an optional.
  • _Null_resettable the value can never be nil, when read but you can set it to know to reset it. This is only apply property.

34- What is JSON/PLIST limits ?

  • We create your objects and then serialized them to disk..
  • It’s great and very limited use cases.
  • We can’t obviously use complex queries to filter your results.
  • It’s very slow.
  • Each time we need something, we need to either serialize or deserialize it.
  • it’s not thread-safe.

35- What is SQLite limits ?

  • We need to define the relations between the tables. Define the schema of all the tables.
  • We have to manually write queries to fetch data.
  • We need to query results and then map those to models.
  • Queries are very fast.

36- What is Realm benefits ?

  • An open-source database framework.
  • Implemented from scratch.
  • Zero copy object store.
  • Fast.

37- How many are there APIs for battery-efficient location tracking ?
There are 3 apis.

  • Significant location changes — the location is delivered approximately every 500 metres (usually up to 1 km)
  • Region monitoring — track enter/exit events from circular regions with a radius equal to 100m or more. Region monitoring is the most precise API after GPS.
  • Visit events — monitor place Visit events which are enters/exits from a place (home/office).

38- What is the Swift main advantage ?
To mention some of the main advantages of Swift:

  • Optional Types, which make applications crash-resistant
  • Built-in error handling
  • Closures
  • Much faster compared to other languages
  • Type-safe language
  • Supports pattern matching

39- Explain generics in Swift ?
Generics create code that does not get specific about underlying data types. Don’t catch this article. Generics allow us to know what type it is going to contain. Generics also provides optimization for our code.

40- Explain lazy in Swift ?
An initial value of the lazy stored properties is calculated only when the property is called for the first time. There are situations when the lazy properties come very handy to developers.

41- Explain what is defer ?
defer keyword which provides a block of code that will be executed in the case when execution is leaving the current scope.

42- How to pass a variable as a reference ?
We need to mention that there are two types of variables: reference and value types. The difference between these two types is that by passing value type, the variable will create a copy of its data, and the reference type variable will just point to the original data in the memory.

43- How to pass data between view controllers?

There are 3 ways to pass data between view controllers.

  1. Segue, in prepareForSegue method (Forward)
  2. Delegate (Backward)
  3. Setting variable directly (Forward)

44- What is Concurrency ?
Concurrency is dividing up the execution paths of your program so that they are possibly running at the same time. The common terminology: process, thread, multithreading, and others. Terminology;

  • Process, An instance of an executing app
  • Thread, Path of execution for code
  • Multithreading, Multiple threads or multiple paths of execution running at the same time.
  • Concurrency, Execute multiple tasks at the same time in a scalable manner.
  • Queues, Queues are lightweight data structures that manage objects in the order of First-in, First-out (FIFO).
  • Synchronous vs Asynchronous tasks

45- Grand Central Dispatch (GCD)
GCD
 is a library that provides a low-level and object-based API to run tasks concurrently while managing threads behind the scenes. Terminology;

  • Dispatch Queues, A dispatch queue is responsible for executing a task in the first-in, first-out order.
  • Serial Dispatch Queue A serial dispatch queue runs tasks one at a time.
  • Concurrent Dispatch Queue A concurrent dispatch queue runs as many tasks as it can without waiting for the started tasks to finish.
  • Main Dispatch Queue A globally available serial queue that executes tasks on the application’s main thread.

46- Readers-Writers
Multiple threads reading at the same time while there should be only one thread writing. The solution to the problem is a readers-writers lock which allows concurrent read-only access and an exclusive write access. Terminology;

  • Race Condition A race condition occurs when two or more threads can access shared data and they try to change it at the same time.
  • Deadlock A deadlock occurs when two or sometimes more tasks wait for the other to finish, and neither ever does.
  • Readers-Writers problem Multiple threads reading at the same time while there should be only one thread writing.
  • Readers-writer lock Such a lock allows concurrent read-only access to the shared resource while write operations require exclusive access.
  • Dispatch Barrier Block Dispatch barrier blocks create a serial-style bottleneck when working with concurrent queues.

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

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

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

48- KVC — KVO
KVC
 adds 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. In KVO, an object can ask to be notified of any changes to a specific property, whenever that property changes value, the observer is automatically notified.

49- Please explain Swift’s pattern matching techniques

  • Tuple patterns are used to match values of corresponding tuple types.
  • Type-casting patterns allow you to cast or match types.
  • Wildcard patterns match and ignore any kind and type of value.
  • Optional patterns are used to match optional values.
  • Enumeration case patterns match cases of existing enumeration types.
  • Expression patterns allow you to compare a given value against a given expression.

50- Explain Guard statement
There are three big benefits to guard statement.

One is avoiding the pyramid of doom, as others have mentioned — lots of annoying if let statements nested inside each other moving further and further to the right. The second benefit is providing an early exit out of the function using break or using return.

The last benefit, guard statement is another way to safely unwrap optionals.



No comments:

Post a Comment