Here are top IOS Interview questions and their answers are given just below to them. These sample questions are framed by experts. These IOS Interview Questions have been designed especially to get you acquainted with the nature of questions you may be asked during your interview for the subject of IOS app Development.

If there is any IOS interview question that have been asked to you, kindly post it in the the comment section.


 

1. What Is Xcode?

Ans:

Xcode is Apple’s integrated development environment (IDE) that you use to design apps for Apple products. It provides various tools to manage your entire development workflow from creating your app, to testing, submitting and optimizing it to the App store.

2. How Multiple Line Comments Can Be Written In Swift?

Ans:

Multiple line comments can be written as forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/).

3. What Are The Collection Types Available In Swift?

Ans:

Multiple line comments can be written as forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/).

4. What Are The Control Transfer Statements Used In Swift?

Ans:

Control transfer statements used in Swift include

  • Break
  • Continue
  • Fallthrough
  • Return

5. What Is The Characteristics Of Switch In Swift?

Ans:

It supports any kind of data and not only Synchronizes it, but also checks for equality. The Switch statement must be exhaustive, which means that you have to cover all possible values for your variable.

6. What Is The Question Mark (?) In Swift?

Ans:

The question mark (?) is used during the declaration of a property. It tells the compiler that this property is optional and whether the property may hold a value or not.

7. What Is The Use Of Double Question Marks (??)?

Ans:

To provide a default value for a variable.

8. What Is The Difference Between Let And Var In Swift?

Ans:

The let keyword is used to declare constants, while var is used for declaring variables.

9. What Is A Guard Statement In Swift?

Ans:

The guard statement evaluates a Boolean condition and proceeds with program execution if the evaluation is true.

10. What Is Gcd? How Is It Used?

Ans:

GCD is the most commonly used API to manage concurrent code and execute operations asynchronously at the UNIX level of the system. GCD provides and manages queues of tasks.



 

11. What Is Synchronous Vs. Asynchronous In Gcd?

Ans:

  • A synchronous function returns only after the completion of a task that it orders.
  • An asynchronous function, on the other hand, returns immediately, ordering the task to be done, but not waiting for it.

12. What Is Mvc?

Ans:

MVC is a design pattern that stands for Model View Controller. This design pattern separates the data from its display, mediated by a View Controller.

13. What Are Delegates?

Ans:

Delegates are a design pattern. A delegate is just an object that another object sends messages to when certain things happen.

14. What Is Core Data?

Ans:

Core Data is an object graph manager, which also has the ability to persist object graphs to a persistent store, on a disk.

15. What Is The Purpose Of The Reuseidentifier?

Ans:

Reusability of an already allocated object.

16. What is Nil Coalescing & Ternary Operator ?

Ans:

It is an easily return an unwrapped optional, or a default value. If we do not have value, we can set zero or default value.

17. What kind of JSONSerialization have ReadingOptions ?

Ans:

  • mutableContainers Specifies that arrays and dictionaries are created as variables objects, not constants.
  • mutableLeaves Specifies that leaf strings in the JSON object graph are created as instances of variable String.
  • allowFragments Specifies that the parser should allow top-level objects that are not an instance of Array or Dictionary.

18. Explain subscripts ?

Ans:

Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence.

19. What is DispatchGroup ?

Ans:

DispatchGroup allows for aggregate synchronization of work. We can use them to submit multiple different work items and track when they all complete, even though they might run on different queues. This behavior can be helpful when progress can’t be made until all of the specified tasks are complete.
The most basic answer: If we need to wait on a couple of asynchronous or synchronous operations before proceeding, we can use DispatchGroup.

20. What is RGR ( Red?—?Green?—?Refactor )?

Ans:

Red, Green and Refactor are stages of the TDD (Test Driven Development).
Red: Write a small amount of test code usually no more than seven lines of code and watch it fail.
Green: Write a small amount of production code. Again, usually no more than seven lines of code and make your test pass.
Refactor: Tests are passing, you can make changes without worrying. Clean up your code.




 

21. Where do we use Dependency Injection ?

Ans:

We use a storyboard or xib in our iOS app, then we created IBOutlets. IBOutlet is a property related to a view. These are injected into the view controller when it is instantiated, which is essentially a form of Dependency Injection.
There are forms of dependency injection: constructor injection, property injection and method injection.

22. Please explain types of notifications.

Ans:

There are two type of notifications: Remote and Local. Remote notification requires connection to a server. Local notifications don’t require server connection. Local notifications happen on device.

23. When is a good time for dependency injection in our projects?

Ans:

There is a few guidelines that you can follow.
Rule 1. Is Testability important to us? If so, then it is essential to identify external dependencies within the class that you wish to test. Once dependencies can be injected we can easily replace real services for mock ones to make it easy to testing easy.
Rules 2. Complex classes have complex dependencies, include application-level logic, or access external resources such as the disk or the network. Most of the classes in your application will be complex, including almost any controller object and most model objects. The easiest way to get started is to pick a complex class in your application and look for places where you initialize other complex objects within that class.
Rules 3. If an object is creating instances of other objects that are shared dependencies within other objects then it is a good candidate for a dependency injection.

24. What kind of order functions can we use on collection types ?

Ans:

map(_:): Returns an array of results after transforming each element in the sequence using the provided closure.
filter(_:): Returns an array of elements that satisfy the provided closure predicate.
reduce(_:_:): Returns a single value by combining each element in the sequence using the provided closure.
sorted(by:): Returns an array of the elements in the sequence sorted based on the provided closure predicate.

25. What allows you to combine your commits ?

Ans:

git squash

26. What is the difference ANY and ANYOBJECT ?

Ans:

According to Apple’s Swift documentation:

  • Any can represent an instance of any type at all, including function types and optional types.
  • AnyObject can represent an instance of any class type.

27. Please explain SOAP and REST Basics differences ?

Ans:

Both of them helps us access Web services. SOAP relies exclusively on XML to provide messaging services. SOAP is definitely the heavyweight choice for Web service access. Originally developed by Microsoft.
REST ( Representational State Transfer ) provides a lighter weight alternative. Instead of using XML to make a request, REST relies on a simple URL in many cases. REST can use four different HTTP 1.1 verbs (GET, POST, PUT, and DELETE) to perform tasks.

28. What is you favorite Visualize Chart library ?

Ans:

Charts has support iOS,tvOS,OSX The Apple side of the cross platform MPAndroidChart.
Core Plot is a 2D plotting framework for macOS, iOS, and tvOS
TEAChart has iOS support

29. Which git command allows us to find bad commits ?

Ans:

git bisect

30. What is CoreData ?

Ans:

Core data is an object graph manager which also has the ability to persist object graphs to the persistent store on a disk. An object graph is like a map of all the different model objects in a typical model view controller iOS application. CoreData has also integration with Core Spotlight.
But Core Data is not thread safe, meaning that, if you load a managed object on one thread, you can’t pass it to another thread and use it safely. This becomes an issue when we want to start introducing threading for performance, so we have two choices.
The first is to keep everything on the main thread, which just means it’s single threaded. Or the second, means making changes on background threads and passing managed object IDs and then loading those objects again on the main thread, but that would mean that you’re on the main thread, which puts us right back where we started. Both of these kind of ruin the point of using threading within Core Data and they can add a lot of complexity to the data layer.
There’s also another option for that and it’s to convert the managed object to a plain old Swift object, or a POSO.


 

31. Could you explain Associatedtype ?

Ans:

If you want to create Generic Protocol we can use associatedtype.

32. Which git command saves your code without making a commit ?

Ans:

git stash

33. Explain Priority Inversion and Priority Inheritance.

Ans:

If high priority thread waits for low priority thread, this is called Priority Inversion. if low priority thread temporarily inherit the priority of the highest priority thread, this is called Priority Inheritance.

34. What is Hashable ?

Ans:

Hashable allows us to use our objects as keys in a dictionary. So we can make our custom types.

35. When do you use optional chaining vs. if let or guard ?

Ans:

We use optional chaining when we do not really care if the operation fails; otherwise, we use if let or guard. Optional chaining lets us run code only if our optional has a value.
Using the question mark operator like this is called optional chaining. Apple’s documentation explains it like this:
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

36. How many different ways to pass data in Swift ?

Ans:

There are many different ways such as Delegate, KVO, Segue, and NSNotification, Target-Action, Callbacks.

37. How do you follow up clean code for this project ?

Ans:

I follow style guide and coding conventions for Swift projects of Github and SwiftLint.

38. Explain to using Class and Inheritance benefits

Ans:

With Overriding provides a mechanism for customization
Reuse implementation
Subclassing provides reuse interface
Modularity
Subclasses provide dynamic dispatch

39. What’s the difference optional between nil and .None?

Ans:

There is no difference. Optional.None (.None for short) is the correct way of initializing an optional variable lacking a value, whereas nil is just syntactic sugar for .None.

40. What is GraphQL ?

Ans:

GraphQL is trying to solve creating a query interface for the clients at the application level. Apollo iOS is a strongly-typed, caching GraphQL client for iOS, written in Swift.



 

41. Explain Common features of Protocols & superclasses

Ans:

  • implementation reuse
  • provide points for customization
  • interface reuse
  • supporting modular design via dynamic dispatch on reused interfaces

42. What is Continuous Integration ?

Ans:

Continuous Integration allows us to get early feedback when something is going wrong during application development. There are a lot of continuous integration tools available.

Self hosted server

  • Xcode Server
  • Jenkins
  • TeamCity

Cloud solutions

  • TravisCI
  • Bitrise
  • Buddybuild

43. What is the difference Delegates and Callbacks ?

Ans:

The difference between delegates and callbacks is that with delegates, the NetworkService is telling the delegate “There is something changed.” With callbacks, the delegate is observing the NetworkService.

44. Explain Linked List

Ans:

Linked List basically consist of the structures we named the Node. These nodes basically have two things. The first one is the one we want to keep. (we do not have to hold single data, we can keep as much information as we want), and the other is the address information of the other node.
Disadvantages of Linked Lists, at the beginning, there is extra space usage. Because the Linked List have an address information in addition to the existing information. This means more space usage.

45. Do you know Back End development ?

Ans:

Depends. I have experienced PARSE and I am awarded FBStart. I decided to learn pure back end. You have two choices. Either you can learn node.js + express.js and mongodb. OR, you can learn Vapor or Kitura.
Don’t you like or use Firebase?
Firebase doesn’t have a path for macOS X developers.
If you want to learn Firebase, please just follow one month of Firebase Google Group.

46. Explain AutoLayout

Ans:

AutoLayout provides a flexible and powerful layout system that describes how views and the UI controls calculates the size and position in the hierarchy.

47. What is the disadvantage to hard-coding log statements ?

Ans:

First, when you start to log. This starts to accumulate. It may not seem like a lot, but every minute adds up. By the end of a project, those stray minutes will equal to hours.
Second, Each time we add one to the code base, we take a risk of injecting new bugs into our code.

48. What is Pointer ?

Ans:

A pointer is a direct reference to a memory address. Whereas a variable acts as a transparent container for a value, pointers remove a layer of abstraction and let you see how that value is stored.

49. Explain Core ML Pros and Cons

Ans:

Pros of Core ML:

  • Really easy to add into your app.
  • Not just for deep learning: also does logistic regression, decision trees, and other “classic” machine learning models.
  • Comes with a handy converter tool that supports several different training packages (Keras, Caffe, scikit-learn, and others).

Cons:

  • Core ML only supports a limited number of model types. If you trained a model that does something Core ML does not support, then you cannot use Core ML.
  • The conversion tools currently support only a few training packages. A notable omission is TensorFlow, arguably the most popular machine learning tool out there. You can write your own converters, but this isn’t a job for a novice. (The reason TensorFlow is not supported is that it is a low-level package for making general computational graphs, while Core ML works at a much higher level of abstraction.)
  • No flexibility, little control. The Core ML API is very basic, it only lets you load a model and run it. There is no way to add custom code to your models.
    iOS 11 and later only.

50. What is pair programming?

Ans:

Pair programming is a tool to share information with junior developers. Junior and senior developer sitting side-by-side this is the best way for the junior to learn from senior developers.




 

51. Explain blocks

Ans:

Blocks are a way of defining a single task or unit of behavior without having to write an entire Objective-C class. they are anonymous functions.

52. What is Keychain ?

Ans:

Keychain is an API for persisting data securly in iOS App.

53. What is the biggest changes in UserNotifications ?

Ans:

  • We can add audio, video and images.
  • We can create custom interfaces for notifications.
  • We can manage notifications with interfaces in the notification center.
  • New Notification extensions allow us to manage remote notification payloads before they’re delivered.

54. Explain the difference between atomic and nonatomic synthesized properties

Ans:

atomic : It is the default behaviour. If an object is declared as atomic then it becomes thread-safe. Thread-safe means, at a time only one thread of a particular instance of that class can have the control over that object.

nonatomic: It is not thread-safe. We can use the nonatomic property attribute to specify that synthesized accessors simply set or return a value directly, with no guarantees about what happens if that same value is accessed simultaneously from different threads. For this reason, it’s faster to access a nonatomic property than an atomic one.

55. Why do we use availability attributes ?

Ans:

Apple wants to support one system version back, meaning that we should support iOS9 or iOS8. Availability Attributes lets us to support previous version iOS.

56. How could we get device token ?

Ans:

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.

57. What is Encapsulation ?

Ans:

Encapsulation is an object-oriented design principles and hides the internal states and functionality of objects. That means objects keep their state information private.

58. What is big-o notation ?

Ans:

An algorithm is an impression method used to determine the working time for an input N size. The big-o notation grade is expressed by the highest value. And the big-o notation is finding the answer with the question of O(n). Here is a cheat sheet and swift algorithm club. For example;
For Loops big-o notation is O(N). Because For Loops work n times.
Variables (var number:Int = 4) big-o notation is O(1).

59. What Is Dependency Management?

Ans:

If we want to integrate open source project, add a framework from a third party project, or even reuse code across our own projects, dependency management helps us to manage these relationships.

60. What is UML Class Diagrams?

Ans:

UML Class Diagram is a set of rules and notations for the specification of a software system, managed and created by the Object Management Group.


 

61. Explain throw

Ans:

We are telling the compiler that it can throw errors by using the throws keyword. Before we can throw an error, we need to make a list of all the possible errors you want to throw.

62. What is Protocol Extensions?

Ans:

We can adopt protocols using extensions as well as on the original type declaration. This allows you to add protocols to types you don’t necessarily own.

63. What is three triggers for a local notification ?

Ans:

Location, Calendar, and Time Interval. A Location notification fires when the GPS on your phone is at a location or geographic region. Calendar trigger is based on calendar data broken into date components. Time Interval is a count of seconds until the timer goes off.

64. Explain Selectors in ObjC

Ans:

Selectors are Objective-C’s internal representation of a method name.

65. What is Remote Notifications attacment’s limits ?

Ans:

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.

66.Name four important data types found in Objective-C.

Ans:

Four data types that you’ll definitely want your developer to be aware of are as follows:

NSString: Represents a string.
CGfloat: Represents a floating point value.
NSInteger: Represents an integer.
BOOL: Represents a boolean.

67. How proficient are you in Objective-C and Swift? Can you briefly describe their differences?

Ans:

When Swift was first launched in 2014, it was aptly described as “Objective-C without the C.” By dropping the legacy conventions that come with a language built on C, Swift is faster, safer, easier to read, easier to maintain, and designed specifically for the modern world of consumer-facing apps. One of the most immediately visible differences is the fact that Objective-C lacks formal support for namespaces, which forces Objective-C code to use two- or three-letter prefixes to differentiate itself. Instead of simple names like “String,” “Dictionary,” and “Array,” Objective-C must use oddities like “NSString,” “NSDictionary,” and “NSArray.”
Another major advantage is that Swift avoids exposing pointers and other “unsafe” accessors when referring to object instances. That said, Objective-C has been around since 1983, and there is a mountain of Objective-C code and resources available to the iOS developer. The best iOS developers tend to be pretty well versed in both, with an understanding that Swift is the future of iOS development.

68. What are UI elements and some common ways you can add them to your app?

Ans:

Buttons, text fields, images, labels, and any other elements that are visible within the application are called UI elements. These elements may be interactive and comprise the user interface (hence the term “UI”) of an application. In iOS development, UI elements can be quickly added through Xcode’s interface builder, or coded from scratch and laid out using NSLayoutConstraints and Auto Layout. Alternatively, each element can also be positioned at exact coordinates using the UIView “(id)initWithFrame:(CGRect)frame” method.

69. Explain the purpose of the reuseIdentifier in the UITableViewCell constructor:

Ans:

(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
The reuseIdentifier tells UITableView which cells may be reused within the table, effectively grouping together rows in a UITableView that differ only in content but have similar layouts. This improves scroll performance by alleviating the need to create new views while scrolling. Instead the cell is reused whenever dequeueReusableCellWithIdentifier: is called.

70. What are some common execution states in iOS?

Ans:

The common execution states are as follows:
Not Running: The app is completely switched off, no code is being executed.
Inactive: The app is running in the foreground without receiving any events.
Active: The app is running in the foreground and receiving events.
Background: The app is executing code in the background.
Suspended: The app is in the background but is not executing any code.



 

71.What is the purpose of managed object context (NSManagedObjectContext) in Objective-C and how does it work?

Ans:

Managed object context exists for three reasons: life-cycle management, notifications, and concurrency. It allows the developer to fetch an object from a persistent store and make the necessary modifications before deciding whether to discard or commit these changes back to the persistent store. The managed object context tracks these changes and allows the developer to undo and redo changes.

72.Determine the value of “x” in the Swift code below. Explain your answer.

Ans:

var a1 = [1, 2, 3, 4, 5]
var a2 = a1
a2.append(6)
var x = a1.count
In Swift, arrays are implemented as structs, making them value types rather than reference types (i.e., classes). When a value type is assigned to a variable as an argument to a function or method, a copy is created and assigned or passed. As a result, the value of “x” or the count of array “a1” remains equal to 5 while the count of array “a2” is equal to 6, appending the integer “6” onto a copy of the array “a1.” The arrays appear in the box below.
a1 = [1, 2, 3, 4, 5]
a2 = [1, 2, 3, 4, 5, 6]

73. Find the bug in the Objective-C code below. Explain your answer.

Ans:

@interface HelloWorldController : UIViewController

@property (strong, nonatomic) UILabel *alert;

@end

@implementation HelloWorldController

– (void)viewDidLoad {
CGRect frame = CGRectMake(150, 150, 150, 50);
self.alert = [[UILabel alloc] initWithFrame:frame];
self.alert.text = @”Hello…”;
[self.view addSubview:self.alert];
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
sleep(10);
self.alert.text = @”World”;
}
);
}

@end
All UI updates must be performed in the main thread. The global dispatch queue does not guarantee that the alert text will be displayed on the UI. As a best practice, it is necessary to specify any updates to the UI occur on the main thread, as in the fixed code below:
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
sleep(10);
dispatch_async(dispatch_get_main_queue(), ^{
self.alert.text = @”World”;
});
});

74.Explain the difference between raw and associated values in Swift.

Ans:

This question tests the developer’s understanding of enumeration in Swift. Enumeration provides a type-safe method of working with a group of related values. Raw values are compile time-set values directly assigned to every case within an enumeration, as in the example detailed below:

enum Alphabet: Int {
case A = 1
case B
case C
}
In the above example code, case “A” was explicitly assigned a raw value integer of 1, while cases “B” and “C” were implicitly assigned raw value integers of 2 and 3, respectively. Associated values allow you to store values of other types alongside case values, as demonstrated below:
enum Alphabet: Int {
case A(Int)
case B
case C(String)
}

75.You’ve just been alerted that your new app is prone to crashing. What do you do?

Ans:

This classic interview question is designed to see how well your prospective programmer can solve problems. What you’re looking for is a general methodology for isolating a bug, and their ability to troubleshoot issues like sudden crashes or freezing. In general, when something goes wrong within an app, a standard approach might look something like this:
Determine the iOS version and make or model of the device.
Gather enough information to reproduce the issue.
Acquire device logs, if possible.
Once you have an idea as to the nature of the issue, acquire tooling or create a unit test and begin debugging.
A great answer would include all of the above, with specific examples of debugging tools like Buglife or ViewMonitor, and a firm grasp of software debugging theory—knowledge on what to do with compile time errors, run-time errors, and logical errors. The one answer you don’t want to hear is the haphazard approach—visually scanning through hundreds of lines of code until the error is found. When it comes to debugging software, a methodical approach is must.

76.On a UITableViewCell constructor:- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

What is the reuseIdentifier used for?

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

77. Explain the difference between atomic and nonatomic synthesized properties?

Ans:

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

78. Explain the difference between copy and retain?

Ans:

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. Copy means the object will be cloned with duplicate values. It is not shared with any one else.

79. What is method swizzling in Objective C and why would you use it?

Ans:

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

80. What’s the difference between not-running, inactive, active, background and suspended execution states?

Ans:

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 is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state.
Active: The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.
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.




 

81. What is a category and when is it used?

Ans:

A category is a way of adding additional methods to a class without extending it. It is often used to add a collection of related methods. A common use case is to add additional methods to built in classes in the Cocoa frameworks. For example adding async download methods to the UIImage class.

82. Can you spot the bug in the following code and suggest how to fix it:

Ans:

@interface MyCustomController : UIViewController

@property (strong, nonatomic) UILabel *alert;

@end

@implementation MyCustomController

– (void)viewDidLoad {
CGRect frame = CGRectMake(100, 100, 100, 50);
self.alert = [[UILabel alloc] initWithFrame:frame];
self.alert.text = @”Please wait…”;
[self.view addSubview:self.alert];
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
sleep(10);
self.alert.text = @”Waiting over”;
}
);
}

@end

All UI updates must be done on the main thread. In the code above the update to the alert text may or may not happen on the main thread, since the global dispatch queue makes no guarantees . Therefore the code should be modified to always run the UI update on the main thread

dispatch_async( 
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
sleep(10);
dispatch_async(dispatch_get_main_queue(), ^{
self.alert.text = @"Waiting over";
});
});

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

Ans:

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.

84. What considerations do you need when writing a UITableViewController which shows images downloaded from a remote server?

Ans:

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.

85. What is a protocol, and how do you define your own and when is it used?

Ans:

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.

@protocol MyCustomDataSource
– (NSUInteger)numberOfRecords;
– (NSDictionary *)recordAtIndex:(NSUInteger)index;
@optional
– (NSString *)titleForRecordAtIndex:(NSUInteger)index;
@end
A common use case is providing a DataSource for UITableView or UICollectionView.

86. What is KVC and KVO? Give an example of using KVC to set a value.

Ans:

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”]

87.What are blocks and how are they used?

Ans:

Blocks are a way of defining a single task or unit of behavior without having to write an entire Objective-C class. Under the covers Blocks are still Objective C objects. They are a language level feature that allow programming techniques like lambdas and closures to be supported in Objective-C. Creating a block is done using the ^ { } syntax:

myBlock = ^{
NSLog(@"This is a block");
}
It can be invoked like so:

myBlock();
It is essentially a function pointer which also has a signature that can be used to enforce type safety at compile and runtime. For example you can pass a block with a specific signature to a method like so:

– (void)callMyBlock:(void (^)(void))callbackBlock;
If you wanted the block to be given some data you can change the signature to include them:

– (void)callMyBlock:(void (^)(double, double))block {

block(3.0, 2.0);
}

88. What mechanisms does iOS provide to support multi-threading?

Ans:

NSThread creates a new low-level thread which can be started by calling the start method.

NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(myThreadMainMethod:)
object:nil];
[myThread start];
NSOperationQueue allows a pool of threads to be created and used to execute NSOperations in parallel. NSOperations can also be run on the main thread by asking NSOperationQueue for the mainQueue.
NSOperationQueue* myQueue = [[NSOperationQueue alloc] init];
[myQueue addOperation:anOperation];
[myQueue addOperationWithBlock:^{
/* Do something. */
}];
GCD or Grand Central Dispatch is a modern feature of Objective-C that provides a rich set of methods and API's to use in order to support common multi-threading tasks. GCD provides a way to queue tasks for dispatch on either the main thread, a concurrent queue (tasks are run in parallel) or a serial queue (tasks are run in FIFO order).
dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(myQueue, ^{
printf("Do some work here.\n");
});

89.What is the Responder Chain?

Ans:

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.

90.What’s the difference between using a delegate and notification?

Ans:

Both are used for sending values and messages to interested parties. A delegate is for one-to-one communication and is a pattern promoted by Apple. In delegation the class raising events will have a property for the delegate and will typically expect it to implement some protocol. The delegating class can then call the _delegate_s protocol methods.

Notification allows a class to broadcast events across the entire application to any interested parties. The broadcasting class doesn’t need to know anything about the listeners for this event, therefore notification is very useful in helping to decouple components in an application.

[NSNotificationCenter defaultCenter] 
postNotificationName:@"TestNotification"
object:self];

 

91. What’s your preference when writing UI’s? Xib files, Storyboards or programmatic UIView?

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

92. How would you securely store private user data offline on a device? What other security best practices should be taken?

Ans:

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.

93. What is MVC and how is it implemented in iOS? What are some pitfalls you’ve experienced with it? Are there any alternatives to MVC?

Ans:

MVC stands for Model, View, Controller. It is a design pattern that defines how to separate out logic when implementing user interfaces. In iOS, Apple provides UIView as a base class for all _View_s, UIViewController is provided to support the Controller which can listen to events in a View and update the View when data changes. The Model represents data in an application and can be implemented using any NSObject, including data collections like NSArray and NSDictionary.

94. A product manager in your company reports that the application is crashing. What do you do?

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

95. What is AutoLayout? What does it mean when a constraint is “broken” by iOS?

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

96. IOS Characteristics

Ans:

Criteria

Result

Type of Operating System

Apple Proprietary based on Macintosh OS X

OS Fragmentation

Tightly integrated with Apple devices

Security

Heightened security guaranteed

97. What JSON framework is supported by iOS (iPhone OS)?

Ans:
SBJson framework is supported by iOS. It is a JSON parser and generator for Objective-C (Objective-C is the primary programming language you use when writing software for OS X and iOS. It’s a superset of the C programming language and provides object-oriented capabilities and a dynamic runtime).
SBJson provides flexible APIs and additional control that makes JSON handling easy.

98. How can we prevent iOS 8 app’s streaming video media from being captured by QuickTime Player on Yosemite during screen recording?

Ans:

HTTP Live Streams that have their media encrypted will not be recorded by QuickTime Player on Yosemite while screen recording. These will black out in the recording.
HTTP Live Streaming: – Send live and on-demand audio and video to iPhone, iPad, Mac, Apple TV, and PC with HTTP Live Streaming (HLS) technology from Apple. Using the same protocol that powers the web, HLS lets you deploy content using ordinary web servers and content delivery networks. HLS is designed for reliability and dynamically adapts to network conditions by optimizing playback for the available speed of wired and wireless connections.

99. What is the relation between iVar and @property?

Ans:

iVar is an instance variable. It cannot be accessed unless we create accessors, which are generated by @property. iVar and its counterpart @property can be of different names.

@interface Box : NSObject{
NSString *boxName;
}
@property (strong) NSString *boxDescription;//this will become another ivar
-(void)aMethod;
@end
@implementation Box
@synthesize boxDescription=boxName;//now boxDescription is accessor for name
-(void)aMethod {
NSLog(@"name=%@", boxName);
NSLog(@"boxDescription=%@",self.boxDescription);
NSLog(@"boxDescription=%@",boxDescription); //throw an error
}
@end

100. Name the framework that is used to construct application’s user interface for iOS

Ans:

The UIKit framework is used to develop application’s user interface. The UIKit framework provides event handling, drawing model, windows, views, and controls, specifically designed for a touch screen interface.
The UIKit framework (UIKit.framework) provides the crucial infrastructure needed to construct and manage iOS apps. This framework provides:

  • window and view architecture to manage an app’s user interface,
  • event handling infrastructure to respond to user input, and
  • an app model to drive the main run loop and interact with the system.

In addition to the core app behaviors, UIKit provides support for the following features:

  • A view controller model to encapsulate the contents of your user interface
  • Support for handling touch and motion-based events
  • Support for a document model that includes iCloud integration
  • Graphics and windowing support, including support for external displays
  • Support for managing the app’s foreground and background execution
  • Printing support
  • Support for customizing the appearance of standard UIKit controls
  • Support for text and web content
  • Cut, copy, and paste support
  • Support for animating user-interface content
  • Integration with other apps on the system through URL schemes and framework interfaces
  • Accessibility support for disabled users
  • Support for the Apple Push Notification service
  • Local notification scheduling and delivery
  • PDF creation
  • Support for using custom input views that behave like the system keyboard
  • Support for creating custom text views that interact with the system keyboard
  • Support for sharing content through email, Twitter, Facebook, and other services


 

101. How can you respond to state transitions on your app?

Ans:

State transitions can be responded to state changes in an appropriate way by calling corresponding methods on app’s delegate object.
For example:
applicationDidBecomeActive( ) method can be used to prepare to run as the foreground app.
applicationDidEnterBackground( ) method can be used to execute some code when the app is running in the background and may be suspended at any time.
applicationWillEnterForeground( ) method can be used to execute some code when your app is moving out of the background
applicationWillTerminate( ) method is called when your app is being terminated.

102. What are the features added in iOS 9?

Ans:

  • Intelligent Search and Siri- Intelligent Search is an excellent mechanism to learn user habits and act on that information- open apps before we need them, make recommendations on places we might like and guide us through our daily lives to make sure we’re where we need to be at the right time.
  • Siri is a personal assistant to the users, able to create contextual reminders and search through photos and videos in new ways. Swiping right from the home screen also brings up a new screen that houses “Siri Suggestions,” putting favorite contacts and apps right on your fingertips, along with nearby restaurant and location information and important news.
  • Deeper search capabilities can show results like sports scores, videos, and content from third-party apps, and you can even do simple conversions and calculations using the search tools on your iPhone or iPad.Performance improvements
  • Many of the built-in apps have been improved.
  • Notes includes new checklists and sketching features
  • Maps now offers transit directions
  • Mail allows for file attachments, and
  • New “News” app that learns your interests and delivers relevant content you might like to read.
  • Apple Pay is being improved with the addition of store credit cards and loyalty cards
  • Leading “Passbook” to be renamed to “Wallet” in iOS 9.
  • San Francisco font, wireless CarPlay support
  • An optional iCloud Drive app, built-in two-factor authentication and optional longer passwords for better security.

103. What is the difference between retain & assign?

Ans:

Assign creates a reference from one object to another without increasing the source’s retain count.

if (_variable != object)
{
[_variable release];
_variable = nil;
_variable = object;
}

Retain creates a reference from one object to another and increases the retain count of the source object.

if (_variable != object)
{
[_variable release];
_variable = nil;
_variable = [object retain];
}

104. What are the different ways to specify layout of elements in UIView?

Ans:

Here are a few common ways to specify the layout of elements in UIView:

  • Using InterfaceBuilder, you can add an XIB file to your project, layout elements within it, and then load the XIB in your application code (either automatically, based on naming conventions, or manually). Also, using InterfaceBuilder you can create a storyboard for your application.
  • You can write your own code to use NSLayoutConstraints and have elements in a view arranged by Auto Layout.
  • You can create CGRects describing the exact coordinates for each element and pass them to UIView’s – (id)initWithFrame:(CGRect)frame method.

105. What is the difference between atomic and non-atomic properties? Which is the default for synthesized properties? When would you use one over the other?

Ans:

  • Properties specified as atomic are guaranteed to always return a fully initialized object. This also happens to be the default state for synthesized properties.

  • While it’s a good practice to specify atomic to remove the potential for confusion, if you leave it off, your properties will still be atomic.

  • This guarantee of atomic properties comes at the cost of performance.

  • However, if you have a property for which you know that retrieving an uninitialized value is not a risk (e.g. if all access to the property is already synchronized via other means), setting it to non-atomic can boost performance.

106. Describe managed object context and it’s function.

Ans:

  • A managed object context (represented by an instance of NSManagedObjectContext) is a temporary “scratchpad” in an application for a (presumably) related collection of objects. These objects collectively represent an internally consistent view of one or more persistent stores.
  • A single managed object instance exists in one and only one context, but multiple copies of an object can exist in different contexts.

The key functions of managed object context include

  • Life-cycle management: Here, the context provides validation, inverse relationship handling and undo/redo
  • Notifications refer to context posts notifications at various points that can be optionally monitored elsewhere in your application.
  • Concurrency is when the Core Data uses thread (or serialized queue) confinement to protect managed objects and managed object contexts.

107. Explain Singleton class.

Ans:

Only one instance of that class is created in the application.

@interface SomeManager : NSObject
+ (id)singleton;
@end
@implementation SomeManager
+ (id)singleton {
static id sharedMyManager = nil;
@synchronized([MyObject class]){
if (sharedMyManager == nil) {
sharedMyManager = [[self alloc] init];
}
}
return sharedMyManager;
}
@end
//using block
+ (id) singleton {
static SomeManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}

108. What is unnamed category

Ans:

Unnamed Category has fallen out of favor now that @protocol has been extended to support @optional methods.
A class extension –
@interface Foo() — is designed to allow you to declare additional private API — SPI or System Programming Interface — that is used to implement the class innards. This typically appears at the top of the .m file. Any methods/properties declared in the class extension must be implemented in the @implementation, just like the methods/properties found in the public @interface.
Class extensions can also be used to re-declare a publicly readonly @property as readwrite prior to @synthesize’ing the accessors.
Example:

Foo.h
@interface Foo:NSObject
@property(readonly, copy) NSString *bar;
-(void) publicSaucing;
@end
Foo.m
@interface Foo()
@property(readwrite, copy) NSString *bar;
- (void) superSecretInternalSaucing;
@end
@implementation Foo
@synthesize bar;
.... must implement the two methods or compiler will warn ....
@end

109. Does Objective-C contain private methods?

Ans:

NO, there is nothing called a private method in Object-C programming. If a method is defined in .m only then it becomes protected. If in .h,it is public.
If you really want a private method then you need to add a local category/ unnamed category/ class extension in the class and add the method in the category and define it in the class.m.

110. What is plist?

Ans:

Plist refers to Property lists that organize data into named values and lists of values using several object types. These types provide you the means to produce data that is meaningfully structured, transportable, storable, and accessible, but still as efficient as possible. Property lists are frequently used by applications running on both Mac OS X and iOS. The property-list programming interfaces for Cocoa and Core Foundation allow you to convert hierarchically structured combinations of these basic types of objects to and from standard XML. You can save the XML data to disk and later use it to reconstruct the original objects.
The user defaults system, which you programmatically access through the NSUserDefaults class, uses property lists to store objects representing user preferences. This limitation would seem to exclude many kinds of objects like as NSColor and NSFont objects, from the user default system. But if objects conform to the NSCoding protocol they can be archived to NSData objects, which are property list–compatible objects.




 

111. What is the purpose of reuseIdentifier? What is the benefit of setting it to a non-nil value?

Ans:

  • The reuseIdentifier is used to group together similar rows in a UITableView; i.e., rows that differ only in their content, but otherwise have similar layouts.
  • A UITableView will normally allocate just enough UITableViewCell objects to display the content visible in the table.
  • If reuseIdentifier is set to a non-nil value then UITableView will first attempt to reuse an already allocated UITableViewCell with the same reuseIdentifier when the table view is scrolled.
  • If reuseIdentifier has not been set, the UITableView will be forced to allocate new UITableViewCell objects for each new item that scrolls into view, potentially leading to laggy animations.

112. What is the difference between an “app ID” and a “bundle ID” and what is each used for?

Ans:

  • An App ID is a two-part string 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 a bundle ID search string is supplied by the developer to match either the bundle ID of a single app or a set of bundle IDs for a group of apps.
  • Since most users consider the App ID as a string, they think it is interchangeable with Bundle ID. Once the App ID is created in the Member Center, you can only use the App ID Prefix that matches the Bundle ID of the Application Bundle.
  • The bundle ID uniquely defines each App. It is specified in Xcode. A single Xcode project can have multiple targets and therefore, output multiple apps. A common use case for this – An app having both lite/free and pro/full versions or branded multiple ways.

113. What is Abstract class in Cocoa?

Ans:

Cocoa doesn’t provide anything called abstract. We can create a class abstract that gets checked only at runtime while it is not checked at compile time.

@interface AbstractClass : NSObject
@end
@implementation AbstractClass
+ (id)alloc{
if (self == [AbstractClass class]) {
NSLog(@"Abstract Class can’t be used");
}
return [super alloc];
@end

114. What is NSURLConnection class? Define its types and use case.

Ans:

There are two ways of using NSURLConnection class. One is asynchronous and the other is synchronous.
An asynchronous connection will create a new thread and performs its download process on the new thread. A synchronous connection will block the calling thread while downloading content and doing its communication.
Many developers think that a synchronous connection blocks the main thread, which is not true. A synchronous connection will always block the thread from which it is fired. If you fire a synchronous connection from the main thread, the main thread will be blocked. But, if you fire a synchronous connection from a thread other than the main thread, it will be like an asynchronous connection and won’t block your main thread.
In fact, the only difference between a synchronous and an asynchronous connection is that at runtime, a thread will be created for the asynchronous connection while it won’t do the same for a synchronous connection.
In order to create an asynchronous connection, we need to do the following:
1. Have our URL in an instance of NSString
2. Convert our string to an instance of NSURL
3. Place our URL in an URL Request of type NSURLRequest, or in the case of mutable URLs, in an instance of NSMutableURLRequest.
4. Create an instance of NSURLConnection and pass the URL request to it.