iOS interview questions
116 questions with answers. 317 open jobs in India ask for iOS.
How could you setup Live Rendering?
With
@IBInspectableand@IBDesignable, it’s possible to build a custom interface for configuring your custom controls and have them rendered in real-time while designing your project.@IBInspectableproperties provide new access to an old feature: user-defined runtime attributes. Currently accessible from the identity inspector, these attributes have been available since before Interface Builder was integrated into Xcode. They provide a powerful mechanism for configuring any key-value coded property of an instance in a NIB, XIB, or storyboard.Built-in Cocoa types can also be extended to have inspectable properties beyond the ones already in Interface Builder’s attribute inspector. If you like rounded corners, you’ll love this UIView extension:
extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } }The attribute
@IBDesignablelets Interface Builder perform live updates on a particular view. This allows seeing how your custom views will appear without building and running your app after each change.To mark a custom view as
IBDesignable, prefix the class name with@IBDesignable(or the IB_DESIGNABLE macro in Objective-C). Your initializers, layout, and drawing methods will be used to render your custom view right on the canvas:@IBDesignable class MyCustomView: UIView { ... }From Awesome iOS Interview (MIT)
Explain: Ways of specifing the layout of elements
Here are a few common ways to specify the layout of elements in a UIView:
- Using
Interface Builder, you can add aXIB fileto 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 your own code to use NSLayoutConstraints to 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.From Awesome iOS Interview (MIT)
- Using
Explain: Size Classes
A size class is a new technology used by iOS to allow you to custom your app for a given device class, based on its orientation and screen size.
There are presently four size classes:
- Horizontal Regular
- Horizontal Compact
- Vertical Regular
- Vertical Compact
From Awesome iOS Interview (MIT)
Explain: Intrinsic Content Size
The Intrinsic Content Size is one of the most powerful features you gain when you opt-in to using Auto Layout to describe your interfaces. When a view has an intrinsic content size, it is promising Auto Layout that it will have a predefined size that the engine can use to calculate and lay out its views
From Awesome iOS Interview (MIT)
What’s the difference between the frame and the bounds?
The boundsof an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0)
The frameof an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.From Awesome iOS Interview (MIT)
When bounds origin will be different from 0,0?
Let's take an example of
UIScrollView: UIScrollView's bounds.origin will not be (0, 0) when its contentOffset is not (0, 0).From Awesome iOS Interview (MIT)
What are layer objects and what do they represent?
Layer objectsare data objects which represent visual content. Layer objects are used by views to render their content. Custom layer objects can also be added to the interface to implement complex animations and other types of sophisticated visual effects.From Awesome iOS Interview (MIT)
Explain: File owner
Two points to be remembered:
- The File owner is the object that loads the nib, i.e. that object which receives the message
loadNibNamed:orinitWithNibName:. - If you want to access any objects in the nib after loading it, you can set an outlet in the file owner.
So you created a fancy view with lots of buttons, subviews etc . If you want to modify any of these views / objects any time after loading the nib FROM the loading object (usually a view or window controller) you set outlets for these objects to the file owner. It's that simple.
This is the reason why by default all View Controllers or Window Controllers act as file owners, and also have an outlet to the main window or view object in the nib file: because duh, if you're controlling something you'll definitely need to have an outlet to it so that you can send messages to it.
The reason it's called file owner and given a special place, is because unlike the other objects in the nib, the file owner is external to the nib and is not part of it. In fact, it only becomes available when the nib is loaded. So the file owner is a stand-in or proxy for the actual object which will later load the nib.
From Awesome iOS Interview (MIT)
- The File owner is the object that loads the nib, i.e. that object which receives the message
Explain: App Life Cycle
application:willFinishLaunchingWithOptions:—This method is your app’s first chance to execute code at launch time.
application:didFinishLaunchingWithOptions:—This method allows you to perform any final initialization before your app is displayed to the user.
applicationDidBecomeActive:—Lets your app know that it is about to become the foreground app. Use this method for any last minute preparation.
applicationWillResignActive:—Lets you know that your app is transitioning away from being the foreground app. Use this method to put your app into a quiescent state.
applicationDidEnterBackground:—Lets you know that your app is now running in the background and may be suspended at any time.
applicationWillEnterForeground:—Lets you know that your app is moving out of the background and back into the foreground, but that it is not yet active.
applicationWillTerminate:—Lets you know that your app is being terminated. This method is not called if your app is suspended.
From Awesome iOS Interview (MIT)
What is the benefit writing tests in iOS apps?
Tests gives us a clear perspective on the API design, by getting into the mindset of being a client of the API before it exists. Good tests serve as great documentation of expected behavior. It gives us confidence to constantly refactor our code because we know that if we break anything our tests fail. If tests are hard to write its usually a sign architecture could be improved. Following RGR ( Red — Green — Refactor ) helps you make improvements early on.
From Awesome iOS Interview (MIT)
Please explain “Arrange-Act-Assert”
AAA is a pattern for arranging and formatting code in Unit Tests. If we were to write XCTests each of our tests would group these functional sections, separated by blank lines: Arrange all necessary preconditions and inputs. Act on the object or method under test. Assert that the expected results have occurred.
From Awesome iOS Interview (MIT)
What is the Test Driven Development of three simple rules?
You are not allowed to write any production code unless it is to make a failing unit test pass. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
From Awesome iOS Interview (MIT)
You’ve just been alerted that your new app is prone to crashing. What do you do?
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.
From Awesome iOS Interview (MIT)
Explain why a compile time error occurs. How can you fix it?
Task: 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 } }Solution: 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’:
struct IntStack { var items = [Int]() mutating func add(x: Int) { items.append(x) // All good! } }From Awesome iOS Interview (MIT)
Spot the bug that occurs in the code
@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"; } ); }Solution: All UI updates must be performed on the main thread. Global dispatch queues do not make any guarantees so code should be modified to run the UI update on the main thread. Here is the fix below:
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ sleep(10); dispatch_async(dispatch_get_main_queue(), ^{ self.alert.text = @"Waiting over"; }); });From Awesome iOS Interview (MIT)
Consider the following code:
Task:
var defaults = UserDefaults.standard() var userPref = defaults.stringForKey("userPref")! printString(userPref) func printString(string: String) { print(string) }Solution: The second line uses the stringForKey method of UserDefaults, which returns an optional, to account for the key not being found, or for the corresponding value not being convertible to a string.
During its execution, if the key is found and the corresponding value is a string, the above code works correctly. But if the key doesn’t exist, or the corresponding value is not a string, the app crashes with the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value The reason is that the forced unwrapping operator ! is attempting to force unwrap a value from a nil optional. The forced unwrapping operator should be used only when an optional is known to contain a non-nil value.
The solution consists of making sure that the optional is not nil before force-unwrapping it:
let userPref = defaults.stringForKey("userPref") if userPref != nil { printString(userPref!) }From Awesome iOS Interview (MIT)
Determine the value of “x” in the Swift code below
Task:
var a1 = [1, 2, 3, 4, 5] var a2 = a1 a2.append(6) var x = a1.countSolution: 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]From Awesome iOS Interview (MIT)
Given two sorted arrays, the task is to merge them in a sorted manner
Input : arr1 = [1, 3, 4, 5]
arr2 = [2, 4, 6, 8] Output : arr3 = [1, 2, 3, 4, 5, 6, 7, 8]- Method 1 (O(n1 * n2) Time and O(1) Extra Space)
Create an array arr3 of size n1 + n2. Copy all n1 elements of arr1 to arr3 Traverse arr2 and one by one insert elements (like insertion sort) of arr3 to arr1. This step take O(n1 * n2) time.
- Method 2 (O(n1 + n2) Time and O(n1 + n2) Extra Space) The idea is to use Merge function of Merge sort.
Create an array arr3 of size n1 + n2. Simultaneously traverse arr1 and arr2. Pick smaller of current elements in arr1 and arr2, copy this smaller element to next position in arr3 and move ahead in arr3 and the array whose element is picked. If there are are remaining elements in arr1 or arr2, copy them also in arr3.
From Awesome iOS Interview (MIT)
Write down the custom method which works similar to reduce() api
sum = array.reduce(0, +) //reduce() here is an ((Int, ((Int, Int) -> Bool)) -> Int) //and the + operator is func +(lhs: Int, rhs: Int) -> Bool, //... or ((Int, Int) -> Bool), so there's no need to define reduce's closure.From Awesome iOS Interview (MIT)
Explain: Application States
The iOS application states are as follows:
Not running state: The app has not been launched or was running but was terminated by the system.
Inactive state:
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. The only time it stays inactive for any period of time is when the user locks the screen or the system prompts the user to respond to some event (such as an incoming phone call or SMS message).
Active state:
The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.
Background state:
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 state:
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.
From Awesome iOS Interview (MIT)
Explain: 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.
From Awesome iOS Interview (MIT)
Explain: Adapter Pattern
An Adapter allows classes with incompatible interfaces to work together. It wraps itself around an object and exposes a standard interface to interact with that object.
From Awesome iOS Interview (MIT)
Explain: Memento Pattern
In Memento Pattern saves your stuff somewhere. Later on, this externalized state can be restored without violating encapsulation; that is, private data remains private. One of Apple’s specialized implementations of the Memento pattern is Archiving.
From Awesome iOS Interview (MIT)
Explain: Factory Method Pattern
Factory Method is used to replace class constructors, to abstract and hide objects initialization so that the type can be determined at runtime, and to hide and contain switch/if statements that determine the type of object to be instantiated.
From Awesome iOS Interview (MIT)
Explain: Responder Chain
A ResponderChain is a hierarchy of objects that have the opportunity to respond to events received.
From Awesome iOS Interview (MIT)
Explain: Observer Pattern
In the Observer pattern, one object notifies other objects of any state changes.
From Awesome iOS Interview (MIT)
Explain: 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.
From Awesome iOS Interview (MIT)
Explain: Decorator Pattern
The Decorator pattern dynamically adds behaviors and responsibilities to an object without modifying its code. It’s an alternative to subclassing where you modify a class’s behavior by wrapping it with another object.
From Awesome iOS Interview (MIT)
Explain: Facade Pattern
The Facade design pattern provides a single interface to a complex subsystem. Instead of exposing the user to a set of classes and their APIs, you only expose one simple unified API.
From Awesome iOS Interview (MIT)
Explain: 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)
- 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.
From Awesome iOS Interview (MIT)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Awesome iOS Interviewby Dasha Korneichuk and contributorsMIT, © 2017 Dasha Korneichuk106 questions
- Stack Overflowby its contributors, named on each answerCC BY-SA10 questions