iOS Interview questions and answers Part10
101.Explain and show examples of SOLID principles?
SOLID principles are relatively old but incredibly useful concepts to apply to any OOP codebase in any language.
SOLID stands for Single Responsibility Principle, Open/Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle. These principles feed into and support each other and are one of the best general design approaches you could take for your code. Let’s go through each of them.
The Single Responsibility Principle (SRP) is the most important principle of the group. It states that every module should have only one responsibility and reason to change. SRP starts with small concrete and specific cases such as a class and/or an object having only one purpose and being used only for only one thing.
The Open/Closed Principle (OCP) states that your modules should be open for extension but closed for modification. It’s one of those things that sounds easy enough but is kind of hard to wrap your head around when you start to think about what it means. Effectively it means that when writing your code you should be able to extend the behaviour of your objects through inheritance, polymorphism, and composition by implementing them using interfaces, abstractions, and dependency injection.
The Liskov Substitution Principle (LSP) states that objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. What that means is that when you inherit from a class or an abstract class or implement an interface (protocol), your objects should be replaceable and injectable wherever that interface or class that you subclassed from was used. This principle is often referred to as design by contract or, as of late in the Swift community, referred to as protocol-oriented programming. The main message of this principle is that you should not violate the contract that your interfaces you subclass from promise to fulfil, and that by subclassing, those subclasses could be used anywhere that the superclass was previously used.
The Interface Segregation Principle (ISP) says many client-specific interfaces are better than one general-purpose interface. It also states that no client should be forced to depend on and implemented methods it does not use. What that means is that when you create interfaces (protocols) that your classes implement, you should strive for and depend on abstraction over specificity, but not until it becomes a waste where you have to implement a bunch of methods your new class doesn’t even use.
The Dependency Inversion Principle (DIP) states, “depend on abstractions, not concretions.” The best example that showcases this principle is the Dependency Injection (DI) technique. With the Dependency Injection technique, when you create an object, you supply and inject all of its dependencies upon its initialisation or configuration rather than let the object create or fetch/find its dependencies for itself.
SOLID principles are the bedrock of good OOP design. Applying these principles will help you build better, more maintainable software. It is highly advised to be well versed in them if you are applying to a senior iOS position.
102.What is data encapsulation, Polymorphism and Abstract?
Data encapsulation: encourages the use of methods to get and set the values of instance variables in a class.But the developer to want to directly access an instance variable without having to go through an accessor method.Data is contained within objects and is not accessible by any other than via methods defined on the class is called data encapsulation.Getters and setters are what make encapsulation elegant in most languages. The point of getters and setters is to explicitly write self-documented code that prevents accidental changes in your code. myObject.getSomeVar() and myObject.setSomeVar(“foo”) explicitly tell whoever is maintaining your code (which can and most of the time will include yourself) that your intentions are clear.
Polymorphism: Ability of base class pointer to call function from derived class at runtime is called polymorphism.The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. Objective-C polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.
Abstract: Cocoa doesn’t provide anything called abstract. We can create a class abstract which gets check only at runtime, compile time this is not checked.
@interface AbstractClass : NSObject
@end
@implementation AbstractClass
+ (id)alloc{
if (self == [AbstractClass class]) { NSLog(@”Abstract Class cant be used”); } return [super alloc]; @end
103.Swift’s Equitable and Comparable Protocols
Equitable: relates too being equal, and “comparable” relates to the comparison between objects. This is important, because how can we be certain that two complex objects are the same? In many circumstances, this is something that you should decide.
Comparable: A protocol that can be applied to a type using the relational operators <, <=, >=, and >
Equitable: A protocol that can be applied to a type to allow value equality
Operand: The value on which an operator is performed
104. Mention what is the characteristics of Switch Enums in Swift?
Switch:It supports any kind of data, and not only synchronise but also checks for equality, when a case is matched in switch, the program exists from the switch case and does not continue checking next cases. So you don’t need to explicitly break out the switch at the end of case.Switch statement must be exhaustive, which means that you have to cover all possible values for your variable, there is no fall through in switch statements and therefore break is not required.
Enums:An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.Enumerations in Swift are much more flexible, and do not have to provide a value for each case of the enumeration. If a value (known as a “raw” value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.Enums can have methods, subscripts, and computed properties. But it cannot have stored properties.Enum with Associated Values.
105.What is method swizzling in Objective C and why would you use it?
Method swizzling allows the implementation of an existing selector to be switched at runtime for a different implementation in a classes dispatch table. Swizzling allows you to write code that can be executed before and/or after the original method. For example perhaps to track the time method execution took, or to insert log statements
#import “UIViewController+Log.h”
@implementation UIViewController (Log)
+ (void)load {
static dispatch_once_t once_token;
dispatch_once(&once_token, ^{
SEL viewWillAppearSelector = @selector(viewDidAppear:);
SEL viewWillAppearLoggerSelector = @selector(log_viewDidAppear:);
Method originalMethod = class_getInstanceMethod(self, viewWillAppearSelector);
Method extendedMethod = class_getInstanceMethod(self, viewWillAppearLoggerSelector);
method_exchangeImplementations(originalMethod, extendedMethod);
});
}
- (void) log_viewDidAppear:(BOOL)animated {
[self log_viewDidAppear:animated];
NSLog(@”viewDidAppear executed for %@”, [self class]);
}
@end
106.how to check crash reports client in iOS app?
Using TestFlight, Crashlytics, Firebase
TestFlight is a platform provided by Apple that allows you to send a testable version of your app to specific beta users. It’s important to realise this is different than the App Store (which is available to the general public). Once you send a user a TestFlight invitation, they must download the TestFlight app where they can download and use a specific version of your app for 60 days.
Now that our build is on iTunes Connect we need to set up Internal and/or External TestFlight Testing.
After processing, select version no to send to tester, fill required information about what to test, what types of testers or group app has to be sent for testing. After submit, after sometime, tester will get email or may get notification about new build with version is ready to test.
107.Property Observers
A property observer observes and responds to changes in a property’s value. With property observer, we don’t need to reset the controls, every time attributes change.
There are two very appropriately named property observers in Swift: willSet, and didSet. They are called exactly when you think they would be, right before and right after setting, respectively. On top of this, they are also implicitly given constants describing the newValue and oldValue respectively.
• willSet comes with a constant parameter that contains the new value, with the default name newValue
• didSet comes with a constant parameter that contains the old value, with the default name oldValue
You can override either of those names, if you wish, but if no name is provided, the defaults are used.
108.Higher order functions in Swift?
Filter, Map, Reduce, flat map, compact Map, higher order functions are functions that takes another function/closure as argument and returns it. You can use these functions to operate on Swift collection types such as Array, set or Dictionary.
Map: The map function has a single argument which is a closure (a function) that it calls as it loops over the collection. This closure takes the element from the collection as an argument and returns a result. The map function returns these results in an array.
Filter: The filter method has a single argument that specifies the include condition. This is a closure that takes as an argument the element from the collection and must return a Bool indicating if the item should be included in the result.
Flat map: is used to flatten a collection of collections. But before flattening the collection, we can apply map to each element.Even more usefully it knows about optional and will remove them from a collection.
Compact Map: If you do compact map a collection containing optional values, it will only consider the non-nil values. This doesn’t do anything on sets and dictionaries as Sets cannot have nil values and for dictionary, the compact map will give an array of tuples with key and value.
Reduce: So, the reduce function takes two arguments.
- One is an initial value which is used to store the initial value or the value or result returned by the closure from each iteration.
- The other one is a closure which takes two arguments, one is the initial value or the result from the previous execution of the closure and the other one is the next item in the collection.
Use Higher order functions where ever possible:
- It improves your swift skills.
- Enhances readability of code.
- More functional programming.
Sort:
let numbers=[4,6,2,5,1,3]
let reverse=numbers.sorted{$0>$1}
print(reverse)
109.Apple Push Notification Services?
The device ID and UDID are different names for the same thing. The device token is used for a server to send notifications to that device using Apple’s Push Notification service — it lets the APN server know which device you’re talking about, but doesn’t have any meaning outside that context.
There are two steps to get device token. First, we must show the user’s permission screen, after we can register for remote notifications. If these steps go well, the system will provide device token. If we uninstall or reinstall the app, the device token would change.
1 An app enables push notifications. The user has to confirm that he wishes to receive these notifications.
- The app receives a “device token”. You can think of the device token as the address that push notifications will be sent to.
- The app sends the device token to your server.
- When something of interest to your app happens, the server sends a push notification to the Apple Push Notification Service, or APNS for short.
- APNS sends the push notification to the user’s device.
When the user’s device receives the push notification, it shows an alert, plays a sound and/or updates the app’s icon. The user can launch the app from the alert. The app is given the contents of the push notification and can handle it as it sees fit.
We can be sent with video or image with push notification. But maximum payload is 4kb. If we want to sent high quality attachment, we should use Notification Service Extension.
110.What is Concurrency and Objectives of Concurrency?
Concurrency:
• Doing multiple things at the same time.
• Taking advantage of number of cores available in multicore CPUs.
• Running multiple programs in parallel.
Objectives of Concurrency:
• Running program in background without hogging CPU.
• Define Tasks, Define Rules and let the system take the responsibility of performing them.
• Improve responsiveness by ensuring that the main thread is free to respond to user events.
• Leverage more cores to do more work in the same amount of time.