About Latest trend

Latest version of iOS, Swift, XCode

Ans : 
As per today (11-Nov-2019),Latest version ofXCode : 11.2
Swift : 5.1
iOS : 13.1
Mac OS : mojave 10.14

1. What’s new in Swift 5?

Answer:
1. isMultiple(of: 2)

var row = 20

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

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

 

iOS Coding Concepts

1. What is the difference between var and let?

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

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

In the first line above, the name variable is explicitly declared since the type of the variable follows the name of the variable. In the second line, the String type is not explicitly declared. However, 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 type.

3. 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!)”)
}
4. Type of optional unwrapping in swift?

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

5. What is Optional binding it swift?

Answer: In Swift, we use a concept known as optional binding to check whether an optional variable has a value or not.

var myName: String?
myName = "Sandesh"

if let name = myName {
    print(name)
}
6. 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.

7. 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 implicity 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"
print(fullName)
8. 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).

Struct vs Class in Swift

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)

 

9: 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()

Question 4: 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 = student.courses! else {return}

1. What is Enum ?
Answer:  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.

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.

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

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.

 

2.  Diff. between Bundle ID and App ID

Answer: 

  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 abc.com and you create an app named Hello, you could assign the string com.abc.Hello 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 …

 

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

14. The following code snippet results in a compile time error:

struct IntStack {
  var items = [Int]()
  func add(x: Int) {
    items.append(x) // Compile time error here.
  }
}

Explain why a compile time error occurs. How can you fix it?

Answer: Structures are value types. By default, the properties of a value type cannot be modified from within its instance methods.

However, you can optionally allow such modification to occur by declaring the instance methods as ‘mutating’; e.g.:

struct IntStack {
  var items = [Int]()
  mutating func add(x: Int) {
    items.append(x) // All good!
  }
}

Consider the following code:

var array1 = [1, 2, 3, 4, 5]
var array2 = array1
array2.append(6)
var len = array1.count

What’s the value of the len variable, and why?

Answer:The len variable is equal to 5, meaning that array1 has 5 elements, whereas array2 has 6 elements:

array1 = [1, 2, 3, 4, 5]
array2 = [1, 2, 3, 4, 5, 6]

When array1 is assigned to array2, a copy of array1 is actually created and assigned.

The reason is that swift arrays are value types (implemented as structs) and not reference types (i.e. classes). When a value type is assigned to a variable, passed as argument to a function or method, or otherwise moved around, a copy of it is actually created and assigned or passed. Note that swift dictionaries are also value types, implemented as structs.

Value types in swift are:

structs (incl. arrays and dictionaries)
enumerations
basic data types (boolean, integer, float, etc.)

 

Outline the class hierarchy for a UIButton until NSObject.

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

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

The three ways to achieve concurrency in iOS are:

  • Threads
  • Dispatch queues
  • Operation queues

3. What is reuseIdentifier?
==> The reuseIdentifier is used to indicate that a cell can be re-used in a UITableView. For example 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.

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.

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

Explain the difference between atomic and nonatomic synthesized properties? 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).

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

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

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

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

17- What is Responder Chain ?

==> A ResponderChain is a hierarchy of objects that have the opportunity to respond to events received. ex. ??????

18- What is Regular expressions ? ==> 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

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

What is the difference between viewDidLoad and viewDidAppear? Which should you use to load data from a remote server to display in the view? 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. What considerations do you need when writing a UITableViewController which shows images downloaded from a remote server? This is a very common task in iOS and a good answer here can cover a whole host of knowledge. The important piece of information in the question is that the images are hosted remotely and they may take time to download, therefore when it asks for “considerations”, you should be talking about:

    • Only download the image when the cell is scrolled into view, i.e. when cellForRowAtIndexPath is called.
  • Downloading 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 we need to check if that cell is still in the view or whether it has been re-used by another piece of data. If it’s been re-used then we should discard the image, otherwise we need to switch back to the main thread to change the image on the cell.

Other good answers will go on to talk about offline caching of the images, using placeholder images while the images are being downloaded. What is a protocol, and how do you define your own and when is it used? 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. What is KVC and KVO? Give an example of using KVC to set a value. 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”] What is the Responder Chain? 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 UIView itself, 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. If you get the opportunity to draw this one out, it’s worth doing to impress the interviewer: What’s your preference when writing UI’s? Xib files, Storyboards or programmatic UIView? 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 visualization 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. How would you securely store private user data offline on a device? What other security best practices should be taken? Again there is no right answer to this, but it’s a great way to see how much a person has dug into iOS security. If you’re interviewing with a bank I’d almost definitely expect someone to know something about it, but all companies need to take security seriously, so here’s the ideal list of topics I’d expect to hear in an answer:

    • 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. Autorelease pool The concept of an autorelease pool is simple, whenever an object instance is marked asautoreleased (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. ViewLifeCycle loadView viewDidLoad viewWillAppear viewWillLayoutSubviews viewDidLayoutSubviews viewDidAppear Design Pattern 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) Test – setup and tear down  — xcassert function A product manager in your company reports that the application is crashing. What do you do? This is a great question in any programming language and is really designed to see how you problem solve. 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. What is AutoLayout? What does it mean when a constraint is “broken” by iOS? 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.

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

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

Security updates in iOS 10

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.
    1. https://www.codementor.io/mattgoldspink/ios-interview-tips-questions-answers-objective-c-du1088nfb

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

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 int he 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.

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

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 apporach 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 interal 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.

What is the difference between a class and an object?

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

What is KVO?

KVO stands for Key-Value Observing. It allows a controller or class to observe when a property value changes.

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

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.

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.

What is a protocol? How do you define your own protocol?

A protocol defines a list of required and optional methods for a class that adopts the protocol to implement. Any class is allowed to implement a protocol so that other classes can send message to it based on the protocol methods without knowing the type of class. An example of how a protocol is defined:

Memory Management

What is the difference between weak and strong?

First, objects are strong by default.

  • Strong means that the reference count will be increased and the reference to it will be maintained through 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)

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

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

Strong means that the reference count will be increased and the reference to it will be maintained through 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. 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.

Design Pattern

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.

What is the delegation pattern?

The delegation pattern is a powerful pattern used in building iOS applications. The basic idea is that one object will act on another object’s behalf or in coordination with another object. 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.

What is MVC?

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)

What is MVVM?

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 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 readibility of your code easier to follow along, the MVVM will be used.

Why array method containObject has id as parameter in ios?

Ans : id is a generic type. This means that the compiler will expect any object type there, and will not enforce restrictions. It can be useful if you’re expecting to use more than one class of objects there. So you can add anything of type id to an NSArray.

So array method containObject has id type as parameter.
– (BOOL)containsObject:(ObjectType)anObject;

Usage :bool bVal = [arr containObject:@5];

 

Design, View, Storyboard 

What is autolayout?

Auto Layout is used to dynamically calculate the size and position of views based on constraints.

16- What’s the difference between the frame and the bounds?

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

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

viewDidLoad is only called when the view is loaded (after loadView is called). viewDidAppear, on the other hand, is called everytime the view appears on the device.

If the data is static for the most part, it can be loaded in viewDidLoad and cached. But if the data is dynamic and likely to change often, it is preferable to use viewDidAppear. In both instances, data should be loaded asynchronously on a background thread to avoid blocking the UI.

Thread management

What is the difference between synchronous and asynchronous task?

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.

Explain the difference between Serial vs Concurrent

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

What is GCD and how is it used?

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.

Unit testing, UI testing

Objective c –

Explain what is synthesized in Objective-C? 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.

What is dynamic in Objective-C ? 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.

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

Objective C :  1. What is @synthesize in Objective-C ? ==> synthesize generates getter and setter methods for your property.

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

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

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

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

fm.smartcloud.io/ios-interview-questions-for-senior-developers-in-2017-a94cc81c8205
https://github.com/onthecodepath/iOS-Interview-Questions/blob/master/README.md

https://www.raywenderlich.com/110982/swift-interview-questions-answers

https://www.toptal.com/swift/interview-questions

 

Access controls in Swift

Ans : 

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.Swift 3, Swift 4There 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.

//module X
public func A(){}
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 

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.

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

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

App Lifecycle 

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.
application:didFinishLaunchingWithOptions
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.
applicationDidBecomeActive
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.
applicationWillResignActive
 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.
applicationDidEnterBackground
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.
applicationWillEnterForeground
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.
applicationWillTerminate
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.

 

 

Memory management

How is memory management handled in iOS?

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.

 

UI / UX / Design related iOS Interview Question 

 

App deployment 

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

Ans : 

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 limit
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 us 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.

What is app thining?

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

 

XCode

How to call segue programmatic?

Ans : 

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

 

Advertisements