iOS Interview Questions Part 2: ObjectiveC đŸ–„

Chetan Aggarwal
15 min readFeb 12, 2018

Earlier, in Part 1 — Differentiate we talked through many terms we use to get better clarity. In this part, we will focus on some specific Objective-C and iOS app development concept.

Q: Define @ synchronized?

The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do—it prevents different threads from acquiring the same lock at the same time.

Official Apple Doc.

Q: What is a selector? How to call a selector?

A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled. A selector by itself doesn’t do anything. It simply identifies a method. The only thing that makes the selector method name different from a plain string is that the compiler makes sure that selectors are unique

Detail: Apple Doc

Q: What is NSBundle and main bundle?

A bundle is a structure used for packaging software on Mac OS X. Applications, frameworks and plug-ins are all different kinds of bundles. Bundles may contain executable code, resources, header files and other stuff (including other bundles) if you so wish.

Bundles are implemented as directory trees with a defined structure. Applications, frameworks and plug-ins each have their own variation on the structure of the tree. However, to the Finder, bundles look like single files.

The main bundle is simply the bundle of the application that is running. So, for instance, the main bundle of the Apple mail program is /Applications/Mail.app.

Apple Developer Doc: NSBundle and mainBundle

Q: Define ‘id’ type in Objective-C?

“id” is a data type of object identifiers in Objective-C, which can be used for an object of any type no matter what class does it have except native or primitive type. “id” is the final supertype of all objects.

Detailed implementation.

Q. What Main function really do in iOS app?

It hand over the control to UIKit framework with the help of UIApplicationMain function.

Q. What are UIAplicationMain function roles?

It creates or starts several core objects of our app. It load UI from available storyboard. It allows custom code(AppDelegate) to do some initial setup. It also starts the app by setting app run loop in motion. We need to provide Storyboard files and custom initialising code to UIAplicationMain function.

Q. What is UIApplication and what it really do?

It is the heart of the iOS app and makes interaction easy between system and other objects of app.

Q: Define NSUserDefaults?

With the NSUserDefaults class, you can save settings and properties related to application or user data. For example, you could save a profile image set by the user or a default color scheme for the application. The objects will be saved in what is known as the iOS “defaults system”. The iOS defaults system is available throughout all of the code in your app, and any data saved to the defaults system will persist through application sessions. This means that even if the user closes your application or reboots their phone, the saved data will still be available the next time they open the app!

With NSUserDefaults you can save objects from the following class types: NSData, NSString, NSNumber, NSDate, NSArray, NSDictionary

If you want to store any other type of object, such as a UIImage, you will typically need to archive it or wrap it in an instance of NSData, NSNumber, or NSString.

Apple Developer Doc

Q: What is APNS payload size?

As per the updated Apple docs the size is 4KB.

  • For regular remote notifications, the maximum size is 4KB (4096 bytes)
  • For Voice over Internet Protocol (VoIP) notifications, the maximum size is 5KB (5120 bytes).

Note:If you are using the legacy APNs binary interface to send notifications instead of an HTTP/2 request, the maximum payload size is 2KB (2048 bytes)

Q: Define Quality of service?

The quality of service API, was actually introduced in iOS 8. QoS can be applied all over iOS as well. One can prioritize queues, thread objects, dispatches queues, and POSIX threads. This is important, since asynchronous work is typically spread out across all of these techniques. By assigning the correct priority for the work these methods perform, iOS apps remain quick, snappy, and responsive.

  • User Interactive: Work that happens on the main thread, such as animations or drawing operations.
  • User Initiated: Work that the user kicks off and should yield immediate results. This work must be completed for the user to continue.
  • Utility: Work that may take a bit and doesn’t need to finish right away. Analogous to progress bars and importing data.
  • Background: This work isn’t visible to the user. Backups, syncs, indexing, etc.
  • Default: The priority level of this QoS falls between user-initiated and utility. Work that has no QoS information assigned is treated as default, and the GCD global queue runs at this level.
  • Unspecified:This represents the absence of QoS information and cues the system that an environmental QoS should be inferred.

Q: What is VoIP notifications?

The official documentation can be found here. Few of the advantages are:

  • app is automatically relaunched if it’s not running when a VoIP push is received
  • device is woken up only when VoIP push occurs (saves battery)
  • VoIP pushes go straight to your app for processing and are delivered without delay
  • app is automatically relaunched if it’s not running when a VoIP push is received

Apple provides us with a framework called PushKit to support using this VoIP push feature. We also need to generate VoIP push certificate also for implementation.

Q: What is Dynamic Dispatch ?

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

Q: Why do we need to specify self to refer to a stored property or a method when writing asynchronous code?

Since the code is dispatched to a background thread we need to capture a reference to the correct object.

Q: What is Deep Linking?

Deep linking is a way to pass data to your application from any platform like, website or any other application. By tapping once on link, you can pass necessary data to your application.

Q: Explain super keyword in child class?

We use the super keyword to call the parent class initializer after setting the child class stored property.

Q: What is the biggest changes in UserNotifications?

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

Q: What are the 3 triggers for a local notification ?

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.

Q: Define Autorelease ?

By Sending an object an autorelease message, it is added to the local AutoReleasePool, and you no longer need to worry about it, because when the AutoReleasePool is destroyed(on main run loop), the object will receive a release message(retain count is decremented by one) and the garbage collector will destroy the object if the RetainCount becomes zero.

Release: retain count is decrease by one when we send release message to object.

Q: Define Autorelease pool ?

An autorelease pool stores objects and sent a release message when the pool itself is drained. If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks. For example, in place of:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Code benefitting from a local autorelease pool. [pool release];

you would write:

@autoreleasepool { // Code benefitting from a local autorelease pool. }

@autoreleasepool blocks are more efficient than using an instance of NSAutoreleasePool directly; you can also use them even if you do not use ARC.

Autorelease pool blocks provide a mechanism whereby you can give up ownership of an object, but avoid the possibility of it being deallocated immediately (such as when you return an object from a method). A drain operation of that pool will happen at the end of every main run loop. This kind of delay-release is necessary in development, sometimes we will want a variable lives longer than its scope (such as a callee function), so we can keep using it later.

In Swift, UIApplicationMain handles the application’s autorelease pool & we don’t have to use autorelease by our self. But in some special cases we might need to add our own autorelease pool.

Where to use autorelease pool? Consider the scenario where you need to process a number of images in a loop.

func processDirectory() {
if let path = NSBundle.mainBundle()
.pathForResource("directory", ofType: "txt") {
for i in 1...90000 {
let data = NSData.dataWithContentsOfFile(
path, options: nil, error: nil)
self.processData()
}
}
}

Here we are using data variable of significant size in a loop. This may take a lot of device’s memory. To optimize this code we can add autorelease pool as follows:

func processDirectory() {
if let path = NSBundle.mainBundle()
.pathForResource("directory", ofType: "txt") {
for i in 1...90000 {
autoreleasepool { () -> Result in
let data = NSData.dataWithContentsOfFile(
path, options: nil, error: nil)
self.processData()
}
}
}
}

Here we are using data in autorelease pool, which gets drained with each iteration of for loop when for loop’s scope ends. As releasing the small chunk of memory in each loop may cause performance issues, we can further optimize it to use autorelease pool in every n iterations instead of each iteration.

Note: When scope of @autoreleasepool ends, all the objects within the scope, is send to main Autoreleasepool, which is drained when the current Run Loop terminates.

Q: What is Method swizzling?

Swizzling is the act of changing the functionality of a method by replacing the implementation of that method with another, usually at runtime. There are many different reasons one might want to use swizzling: introspection, overriding default behavior, or maybe even dynamic method loading. This dynamic program modification is similar to monkey patching, a concept supported by other dynamic languages.

Implementation example by Michael Marvis.

Q: What is NSCoding?

Q: How to accessing variable in blocks?

By using __block Storage Type. Detail: Apple Doc

Q: Where should we perform UI task in GCD?

Main queues are perfect for updating UI and fetching our images, whereas any other heavy task should run on the background thread.

dispatch_async(dispatch_get_global_queue(0, 0), ^{
//load your data here.
dispatch_async(dispatch_get_main_queue(), ^{
//update UI in main thread.
});
});

Q: What is fast enumeration ?

Several Cocoa classes, including the collection classes, adopt the NSFastEnumeration protocol. You use it to retrieve elements held by an instance using a syntax similar to that of a standard C for loop, as illustrated in the following example:

NSArray *anArray = // get an array;
for (id element in anArray) {
/* code that acts on the element */
}

Q: Difference between ‘+’ and ‘-’ notation in methods?

Instance methods begin with ‘-’ and class level methods begin with ‘+’ in Objective-C

Q: Class vs Instance vs Static methods

Instance methods are functions that belong to instances of a particular class, structure, or enumeration. They support the functionality of those instances, either by providing ways to access and modify instance properties, or by providing functionality related to the instance’s purpose.

Class methods are called on the type itself, also known as type methods. You indicate type methods for classes by writing the keyword class before the method’s func keyword, and type methods for structures and enumerations by writing the keyword static before the method’s func keyword.

Subclasses can override class methods since they are are dynamically dispatched; we cannot override staticmethods.class properties will theoretically function in the same way (subclasses can override them), but they're not possible in Swift yet. Static can be considered as “Class final”

Apple Doc.

Q: Define Cocoapods ?

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. CocoaPods is built with Ruby and is installable with the default Ruby available on OS X.

The dependencies for your projects are specified in a single text file called a Podfile. CocoaPods will resolve dependencies between libraries, fetch the resulting source code, then link it together in an Xcode workspace to build your project.

Installation guide.

Note: A dependency manager makes it easy to add, remove, update and manage third-party dependencies used by your app.

Q: What is Test flight ?

TestFlight Beta Testing is an Apple product that makes it easy to invite users to test your iOS, watchOS and tvOS apps before you release them into the App Store. You can invite up to 10,000 testers using just their email address.

The TestFlight SDK additionally allowed developers to receive remote logs, crash reports and tester feedback.

Q: What are NSXMLParserDelegate ?

Apple Docs

Q: What is HTTP protocol ?

HTTP is the application protocol, or set of rules, web sites use to transfer data from the web server to client. The client (your web browser or app) use to indicate the desired action:

  • GET: Used to retrieve data, such as a web page, but doesn’t alter any data on the server.
  • HEAD: Identical to GET but only sends back the headers and none of the actual data.
  • POST: Used to send data to the server, commonly used when filling a form and clicking submit.
  • PUT: Used to send data to the specific location provided.
  • DELETE: Deletes data from the specific location provided.

Q: What is the major purposes of Frameworks?

Frameworks have three major purposes:

  • Code encapsulation
  • Code modularity
  • Code reuse

You can share your framework with your other apps, team members, or the iOS community. When combined with Swift’s access control, frameworks help define strong, testable interfaces between code modules.

Q: Which APIs are used for battery-efficient location tracking ?

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

Q: What is Continuous Integration ?

Continuous Integration (CI) is a development practice that requires developers to integrate code into a shared repository several times a day. Each check-in is then verified by an automated build, allowing teams to detect problems early. There are a lot of continuous integration tools available like — Xcode server, Jenkins, Travis, Fastlane etc.

Q: What is Keychain ?

Keychain is an API for persisting data securly in iOS App. There is a good library — Locksmith

Q: What’s accessibilityHint?

accessibilityHint describes the results of interacting with a user interface element. A hint should be supplied only if the result of an interaction is not obvious from the element’s label.

Q: Explain UNNotification Content?

UNNotification Content stores the notification content in a scheduled or delivered notification. It is read-only.

Q: Explain CAEmitterLayer and CAEmitterCell?

UIKit provides two classes for creating particle effects: CAEmitterLayer and CAEmitterCell. The CAEmitterLayer is the layer that emits, animates and renders the particle system. The CAEmitterCell represents the source and defines the direction and properties of the emitted particles.

Q: Explain In-app Purchase products and subscriptions?

  • Consumable products: can be purchased more than once and used items would have to re-purchase.
  • Non-consumable products: user would be able to restore this functionality in the future, should they need to reinstall the app for any reason. We can also add subscriptions to our app.
  • Non-Renewing Subscription: Used for a certain amount of time and certain content.
  • Auto-Renewing Subscription: Used for recurring monthly subscriptions.

Q: What is HealthKit ?

HealthKit is a framework on iOS. It stores health and fitness data in a central location. It takes in data from multiple sources, which could be different devices. It allows users to control access to their data and maintains privacy of user data. Data is synced between your phone and your watch.

Q: Explain Neural networks with Core ML ?

Neural networks and deep learning currently provide the best solutions to many problems in image recognition, speech recognition, and natural language processing.

Core ML is an iOS framework comes with iOS 11, helps to process models in your apps for face detection. For more information follow this guideline https://developer.apple.com/machine-learning/

Q: Explain libssl_iOS and libcrypto_iOS ?

These files are going to help us with on device verification of our receipt verification files with In-App purchases.

Q: What kind of benefits does Xcode server have for developers?

Xcode server will automatically check out our project, build the app, run tests, and archive the app for distribution.

Q: Explain AVFoundation framework?

We can create, play audio and visual media. AVFoundation allows us to work on a detailed level with time-based audio-visual data. With it, we can create, edit, analyze, and re-encode media files. AVFoundation has two sets of API, one that’s video, and one that is audio.

Q: How is the app delegate is declared by Xcode project template ?

It is declared as a subclass of UIResponder by Xcode project template.

Q: What is purpose of UIWindow object?

The presentation of one or more views on a screen is coordinate by UIWindow object.

Q: What are layer objects and what do they represent?

Layer objects are data objects which represent visual content. Layer objects are used by view to render their content. They can also be added to implement complex animation and other types of sophisticated visual effects.

Q: Define UIViewConroller Life Cycle?

iOS 10,11 (Swift 3.1,Swift 4.0)

According to UIViewController in Apple developer’s Documentation,

1. loadView(): This is where subclasses should create their custom view hierarchy if they aren’t using a nib. Should never be called directly.

2. loadViewIfNeeded(): Loads the view controller’s view if it has not already been set.

3. viewDidLoad(): Called after the view has been loaded. For view controllers created in code, this is after -loadView. For view controllers unarchived from a nib, this is after the view is set.

4. viewWillLayoutSubviews(): Called just after the view controller’s view’s layoutSubviews method is invoked. Subclasses can implement as necessary.

5. viewDidLayoutSubviews():Called when the size, position and constraints are applied to the all objects.

6. viewWillAppear(_ animated: Bool): Called when the view is about to made visible. Default does nothing

7. viewDidAppear(_ animated: Bool): Called when the view has been fully transitioned onto the screen. Default does nothing

8. viewWillDisappear(_ animated: Bool): Called when the view is dismissed, covered or otherwise hidden. Default does nothing

9. viewDidDisappear(_ animated: Bool): Called after the view was dismissed, covered or otherwise hidden. Default does nothing

10. viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator): Called when the view is Transitioning.

11. willMove(toParentViewController parent: UIViewController?)

12. didMove(toParentViewController parent: UIViewController?)

These two methods are public for container subclasses to call when transitioning between child controllers. If they are overridden, the overrides should ensure to call the super.

The parent argument in both of these methods is nil when a child is being removed from its parent; otherwise it is equal to the new parent view controller.

13. didReceiveMemoryWarning():Called when the parent application receives a memory warning. On iOS 6.0 it will no longer clear the view by default.

Q: Define differenct App State?

Not running:The app has not been launched or was running but was terminated by the system.

Inactive(Foreground): 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(Foreground): The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.

Souce: Apple Docs

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. For information about how to execute code while in the background, see Background Execution.

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.

Q: Define App Delegate Lifecycle?

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.

Apple App Life Cycle Doc

Q: Define Retain Cycle?

Retain Cycle is the condition when 2 objects keep a reference to each other and are retained, it creates a retain cycle since both objects try to retain each other, making it impossible to release.

Nice article by Matt Gallagher.

Where to go next ⏩

Thank you for reading đŸ§‘đŸ»â€đŸ’»

Be sure to clap đŸ‘đŸŒ and follow đŸš¶đŸ»â€â™‚ïž

Questions❓Feedback đŸ“« — please drop you comments 💭

If you like this article, feel free to share it with your friends 📹

Follow me: Linkedin | X(Twitter) | Github đŸ€đŸŒ

--

--