iOS

iOS

Top Interview Questions

About iOS

 

iOS: Apple’s Mobile Operating System

iOS is a mobile operating system developed by Apple Inc., specifically designed to run on Apple hardware, including the iPhone, iPad, and iPod Touch. Known for its intuitive interface, robust security, and seamless integration with the Apple ecosystem, iOS has grown to become one of the most influential mobile operating systems globally. It combines performance, design, and functionality in a way that appeals to millions of users and developers worldwide.

History and Evolution of iOS

iOS, originally named iPhone OS, was first introduced in 2007 alongside the first iPhone. At that time, smartphones were dominated by BlackBerry OS, Symbian, and Windows Mobile. Apple revolutionized the mobile industry by providing a touchscreen-based interface without a physical keyboard, coupled with an operating system that was optimized for touch interactions.

Over the years, Apple rebranded iPhone OS as iOS in 2010 with the release of iOS 4. This rebranding coincided with several key innovations, such as multitasking, FaceTime, and the introduction of the iPad as a major device in Apple’s portfolio. iOS has since gone through numerous iterations, each improving performance, enhancing user experience, and introducing new features like Siri (iOS 5), Control Center (iOS 7), Dark Mode (iOS 13), and more recently, advanced AI-powered features and system-wide enhancements.

Architecture of iOS

iOS is built on a layered architecture that ensures reliability, security, and efficiency. Its architecture can be broadly divided into four layers:

  1. Cocoa Touch Layer:
    This is the topmost layer that provides frameworks for building applications. Cocoa Touch offers essential APIs for touch-based input, gestures, multitasking, notifications, and high-level services like camera and location. It is primarily used by developers to design interactive applications that adhere to Apple’s human interface guidelines.

  2. Media Layer:
    The Media layer provides graphics, audio, and video support. It includes technologies like Core Graphics, Core Animation, Core Image, AVFoundation, and OpenGL/Metal for 3D graphics. This layer allows developers to create visually appealing and media-rich applications while ensuring efficient rendering and performance.

  3. Core Services Layer:
    This layer provides fundamental services and data management capabilities. Key components include Core Data for database management, Foundation framework for standard utilities, and CloudKit for iCloud integration. Core Services also handles networking, threading, and other system-level services that ensure apps can run smoothly.

  4. Core OS Layer:
    The Core OS layer interacts directly with the device hardware. It includes the kernel, device drivers, and low-level features like security, file system management, networking, and power management. This layer ensures that iOS runs securely and efficiently on Apple devices.

This layered architecture allows iOS to provide a balance of performance, user experience, and security, which is critical for mobile devices with limited resources compared to desktop computers.

Key Features of iOS

iOS is distinguished by several unique features that make it stand out among mobile operating systems:

1. User Interface and Experience

iOS is renowned for its clean, intuitive, and user-friendly interface. The operating system follows strict Human Interface Guidelines (HIG), which provide consistency across apps. Features like the home screen, dock, gestures, and animations create a seamless and responsive user experience.

2. App Store and Ecosystem

Apple’s App Store is the primary distribution platform for iOS apps. It provides a secure and curated environment for users to download applications. Developers benefit from a large audience and monetization opportunities through app purchases, subscriptions, and in-app purchases. The App Store has millions of apps covering productivity, gaming, education, and entertainment.

3. Security and Privacy

Security is a cornerstone of iOS. Apple implements features like Data Encryption, Secure Boot, App Sandbox, Face ID, and Touch ID to protect user data. iOS also enforces strict app review policies to prevent malicious applications from entering the App Store. Features like privacy labels, permission prompts, and on-device processing for AI tasks further enhance user privacy.

4. Integration with Apple Ecosystem

iOS devices seamlessly integrate with other Apple products and services. Features like Handoff, Continuity, AirDrop, and iCloud allow users to switch devices effortlessly, share files, and maintain synchronized data across multiple devices. This integration creates a cohesive experience that enhances productivity and convenience.

5. Siri and AI Capabilities

Siri, Apple’s virtual assistant, is integrated deeply into iOS. It enables voice commands, smart suggestions, and automation through Shortcuts. With each iOS iteration, Siri has grown smarter, offering natural language understanding, proactive suggestions, and integration with third-party apps.

6. Regular Updates and Support

Apple provides regular updates for iOS, often supporting devices for up to five to six years. This long-term support ensures that users receive new features, security patches, and performance improvements without needing to purchase a new device. This approach contrasts with many other mobile operating systems that provide shorter support cycles.

iOS Development

iOS development involves creating applications using Apple’s programming languages and frameworks. Key aspects include:

Programming Languages

  • Objective-C: One of the original languages used for iOS development. It is a superset of C, offering object-oriented features.

  • Swift: Introduced in 2014, Swift is a modern programming language designed to be safe, fast, and expressive. It is now the preferred language for iOS development.

Development Environment

iOS apps are primarily developed using Xcode, Apple’s integrated development environment (IDE). Xcode provides tools for designing user interfaces, coding, debugging, and testing apps. The IDE also includes a simulator to test apps on different device configurations.

Frameworks and APIs

Developers use various frameworks provided by Apple, including:

  • UIKit: For building user interfaces.

  • Core Data: For data persistence.

  • AVFoundation: For audio and video.

  • Core ML: For machine learning integration.

  • ARKit: For augmented reality experiences.

App Lifecycle and Distribution

iOS apps go through a defined lifecycle, including states like Not Running, Inactive, Active, Background, and Suspended. Understanding this lifecycle is crucial for optimizing performance and resource management.

Once an app is ready, developers submit it to the App Store for review. Apple’s review process ensures compliance with guidelines and security standards before an app becomes publicly available.

iOS Devices

iOS runs on a range of Apple devices, including:

  • iPhone: The flagship mobile device for which iOS was originally developed.

  • iPad: iPads run a variant of iOS called iPadOS, optimized for larger screens and multitasking.

  • iPod Touch: A portable media player and gaming device.

  • Apple Watch (watchOS) and Apple TV (tvOS): While technically running distinct operating systems, they share many frameworks and design principles with iOS.

Advantages of iOS

  1. Consistent User Experience: Apple’s strict design guidelines ensure that users enjoy a consistent and smooth experience across all devices.

  2. Security: Strong encryption, regular updates, and app review processes reduce the risk of malware and data breaches.

  3. High Performance: iOS is optimized for Apple hardware, resulting in fast and responsive devices.

  4. Longevity: Devices receive software updates for many years, ensuring longevity and reduced e-waste.

  5. Developer Support: Comprehensive tools, documentation, and frameworks make it easier for developers to create high-quality apps.

Challenges and Criticisms

Despite its strengths, iOS faces some criticisms:

  • Closed Ecosystem: iOS restricts app installations to the App Store, limiting flexibility for users who want more control.

  • Hardware Dependency: iOS can only run on Apple devices, which are often expensive compared to alternatives.

  • Customization Limitations: Unlike Android, iOS allows limited customization of the user interface.

Fresher Interview Questions

 

1. What is iOS?

Answer:
iOS is Apple’s mobile operating system used in iPhone, iPad, and iPod Touch devices. It is built on the Darwin kernel and provides a smooth user interface, security features, and performance optimization. iOS supports applications developed using Swift or Objective-C.


2. What are the main features of iOS?

Answer:

  • Multitasking: Supports running multiple apps in the background.

  • User-friendly interface: Smooth touch gestures and simple UI design.

  • Security: Data protection with encryption and app sandboxing.

  • Regular updates: Apple frequently releases new iOS versions.

  • App Store: Centralized platform for app distribution.

  • Performance: Optimized for Apple hardware ensuring smooth operation.


3. What is the difference between iOS and Android?

Feature iOS Android
OS Type Closed source Open source
Programming Swift / Objective-C Java / Kotlin
App Store App Store Google Play Store
Customization Limited Highly customizable
Hardware Only Apple devices Multiple manufacturers
Updates Released for all devices at once Fragmented across devices

4. What languages are used for iOS development?

Answer:

  • Swift: Modern, fast, and safe language designed by Apple.

  • Objective-C: Older language still used in legacy applications.


5. What is Swift?

Answer:
Swift is Apple’s programming language introduced in 2014 for iOS, macOS, watchOS, and tvOS app development. It is safe, fast, and expressive and supports modern programming paradigms like object-oriented and functional programming.


6. What is the difference between Swift and Objective-C?

Feature Swift Objective-C
Syntax Modern and clean Older and verbose
Safety Safe with null handling Less safe
Speed Faster Slightly slower
Popularity Increasing Decreasing
Memory Management Automatic Reference Counting (ARC) ARC and manual options

7. What is Xcode?

Answer:
Xcode is Apple’s Integrated Development Environment (IDE) used to develop iOS, macOS, watchOS, and tvOS applications.
Key Features:

  • Code editor

  • Interface builder

  • Simulator for testing apps

  • Debugging tools

  • Performance analysis tools


8. What is MVC in iOS?

Answer:
MVC stands for Model-View-Controller, an architecture pattern used in iOS app development:

  • Model: Manages app data and business logic.

  • View: Displays the user interface.

  • Controller: Handles interactions between the Model and View.


9. What are Storyboards in iOS?

Answer:
Storyboards are visual representations of the app’s user interface in Xcode. They show screens (view controllers) and their connections (segues).
Benefits:

  • Easy to design UI

  • Supports drag-and-drop interface elements

  • Helps visualize navigation flow


10. What is a Delegate in iOS?

Answer:
A delegate is a design pattern in iOS used to communicate between objects. One object can delegate responsibilities to another object.
Example: UITableViewDelegate handles table view events like row selection.


11. What is the difference between frame and bounds in iOS?

Term Description
Frame The view’s size and position relative to its superview.
Bounds The view’s size and position relative to itself.

12. What is IBOutlet and IBAction?

  • IBOutlet: Connects UI elements from storyboard to Swift code.

  • IBAction: Connects user actions (like button taps) to Swift functions.


13. What is Auto Layout?

Answer:
Auto Layout is a system that allows developers to create adaptive UI for different screen sizes and orientations. Constraints define relationships between UI elements to adjust layouts automatically.


14. What is the difference between weak and strong in Swift?

Term Description
Strong Keeps a reference to an object in memory.
Weak Doesn’t prevent object from being deallocated; avoids retain cycles.

15. What is ARC in iOS?

Answer:
ARC (Automatic Reference Counting) manages memory in Swift and Objective-C. It automatically tracks and manages object lifetimes to prevent memory leaks.


16. What are View Controllers?

Answer:
View Controllers manage a single screen in an app. They handle user interactions, update UI elements, and communicate with the model.
Types:

  • UIViewController – Base class

  • UITableViewController – For table views

  • UICollectionViewController – For collection views


17. What are the types of iOS applications?

  • Native App: Developed using Swift or Objective-C for iOS.

  • Hybrid App: Uses web technologies like HTML, CSS, and JavaScript wrapped in a native shell.

  • Web App: Accessed via the browser, not installed on the device.


18. What is the difference between frame and autoresizing?

  • Frame: Absolute position of a view.

  • Autoresizing: Allows the view to resize automatically based on its parent view.


19. What is the difference between synchronous and asynchronous tasks?

Term Description
Synchronous Task runs in order, blocking the main thread until finished.
Asynchronous Task runs in the background, doesn’t block main thread.

20. What is Core Data?

Answer:
Core Data is a framework for managing object graphs and persisting data in iOS apps. It allows developers to store data in a database-like system without writing SQL queries.


21. What is the difference between frame and center in iOS?

  • Frame: Position and size of the view.

  • Center: The point representing the center of the view.


22. What is the difference between nil and Optional in Swift?

  • Optional: A variable that may or may not have a value.

  • Nil: Represents no value assigned to an optional variable.


23. What is GCD (Grand Central Dispatch)?

Answer:
GCD is a framework for concurrent programming in iOS. It allows executing tasks asynchronously on different queues (main, background).

Example:

DispatchQueue.global().async {
    // Background task
    DispatchQueue.main.async {
        // Update UI
    }
}

24. What is the difference between weak, unowned, and strong references?

  • Strong: Default, keeps object in memory.

  • Weak: Does not prevent deallocation, used in circular references.

  • Unowned: Similar to weak but assumes object always exists; crashes if object is nil.


25. What is the App Life Cycle in iOS?

Answer:
The iOS app life cycle represents the states an app goes through:

  1. Not running: App not launched.

  2. Inactive: App in foreground but not receiving events.

  3. Active: App in foreground and running.

  4. Background: App running in the background.

  5. Suspended: App in memory but not executing code.


26. What are Notifications in iOS?

Answer:
Notifications allow apps to communicate asynchronously:

  • Local Notifications: Scheduled by the app itself.

  • Push Notifications: Sent by a server through APNs (Apple Push Notification service).


27. What is the difference between struct and class in Swift?

Feature Struct Class
Reference/Value type Value type Reference type
Inheritance No Yes
Memory Stack Heap
Mutability var required Can modify properties

28. What is the difference between frame and bounds?

We already covered this, but to recap:

  • Frame: Relative to superview.

  • Bounds: Relative to the view itself.


29. What is the difference between UITableView and UICollectionView?

  • UITableView: Single column, vertical scrolling list.

  • UICollectionView: Grid-based or custom layouts, more flexible.


30. What is the difference between let and var in Swift?

Answer:

  • let: Declares a constant. Its value cannot be changed after initialization.

  • var: Declares a variable. Its value can be modified after initialization.

Example:

let name = "Yash"  // constant
var age = 25        // variable
age = 26            // allowed

31. What is a Protocol in Swift?

Answer:
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task. Classes, structs, or enums can adopt protocols.

Example:

protocol Drivable {
    func drive()
}

class Car: Drivable {
    func drive() {
        print("Car is driving")
    }
}

32. What is the difference between extension and subclass?

Feature Extension Subclass
Purpose Adds functionality to existing class/struct Creates a new class based on a parent class
Inheritance Not required Required
Access to properties Limited to public/protected Can access all properties of parent

33. What is the difference between synchronous and asynchronous execution?

Answer:

  • Synchronous: Blocks the current thread until the task completes.

  • Asynchronous: Runs in the background; allows UI and other tasks to continue.

Example with GCD:

DispatchQueue.global().async { // asynchronous
    // background task
}

34. What is the difference between strong, weak, and unowned references in Swift?

Answer:

  • Strong: Keeps a reference to an object; prevents deallocation.

  • Weak: Does not keep the object in memory; automatically becomes nil if object deallocates.

  • Unowned: Similar to weak but assumes object always exists; crashes if nil.


35. What is the difference between View and Layer?

  • View: Displays UI and handles user interactions.

  • Layer: Core Animation layer responsible for rendering and animations; each view has an underlying layer.


36. What is the difference between UITableView and UICollectionView?

  • UITableView: Vertical scrolling list with single-column cells.

  • UICollectionView: Flexible layout; supports grid, horizontal, and custom layouts.


37. What is the difference between frame, bounds, and center in iOS?

Term Description
Frame Position and size relative to superview
Bounds Position and size relative to itself
Center The center point of the view

38. What is NotificationCenter?

Answer:
NotificationCenter allows communication between objects in an app without tightly coupling them. It uses observers to listen for notifications.

Example:

NotificationCenter.default.addObserver(self, selector: #selector(update), name: Notification.Name("UpdateData"), object: nil)

39. What is the difference between push and modal view controllers?

  • Push: Adds a view to the navigation stack. Back button appears.

  • Modal: Presents a new view controller over the current one. Usually requires dismissal.


40. What is the difference between weak self and unowned self in closures?

  • Weak self: Prevents strong reference cycle; optional.

  • Unowned self: Prevents strong reference cycle; assumes self always exists (non-optional).


41. What are Swift Optionals?

Answer:
Optionals allow a variable to hold a value or no value (nil). Useful to avoid crashes.

Example:

var name: String? = "Yash"
name = nil  // valid

42. What is the difference between guard and if let in Swift?

  • if let: Used to unwrap optionals conditionally.

  • guard let: Ensures a value exists; else executes early exit (return, break).

Example:

func process(name: String?) {
    guard let unwrappedName = name else { return }
    print(unwrappedName)
}

43. What is the difference between class and struct in Swift?

Feature Class Struct
Type Reference Value
Inheritance Yes No
Memory Heap Stack
Mutability Can modify even in let Requires var

44. What is the difference between didSet and willSet?

  • willSet: Called before a property changes.

  • didSet: Called after a property changes.


45. What is the difference between lazy and regular properties?

  • lazy: Initialized only when first accessed. Useful for heavy objects.

  • regular: Initialized immediately when the instance is created.


46. What is the difference between App Sandbox and normal apps?

  • Sandboxed app: Limited access to resources, files, and system. Ensures security.

  • Normal app: No restriction, can access files, resources freely (not in iOS, only conceptually).


47. What are iOS app architectures?

  1. MVC (Model-View-Controller): Apple default; separates data, UI, and logic.

  2. MVVM (Model-View-ViewModel): Improves testing and code separation.

  3. VIPER: Layered architecture for large apps.

  4. Clean Architecture: Decouples presentation, domain, and data layers.


48. What is the difference between Main Thread and Background Thread?

  • Main Thread: Handles UI and user interaction; must be fast.

  • Background Thread: Handles heavy tasks like network requests or DB operations.


49. What is the difference between Synchronous and Asynchronous network calls?

Feature Synchronous Asynchronous
Execution Blocks until response Runs in background
UI Impact Freezes UI UI stays responsive
Usage Rare Common (URLSession)

 

Experienced Interview Questions

 

1. What are the main differences between Swift 5 and Swift 4?

Answer:

  • ABI Stability: Swift 5 introduced ABI (Application Binary Interface) stability for better compatibility.

  • Standard Library: Swift 5 includes a smaller, more stable standard library.

  • String Handling: Strings in Swift 5 support raw strings and improved Unicode support.

  • Result Type: Swift 5 introduces Result<T, Error> for cleaner error handling.


2. Explain memory management in iOS and ARC

Answer:

  • iOS uses Automatic Reference Counting (ARC) to manage memory.

  • ARC keeps a count of strong references to objects; when the count reaches 0, the object is deallocated.

  • Strong references: Default; keep the object alive.

  • Weak references: Avoid retain cycles; do not increase reference count.

  • Unowned references: Similar to weak but non-optional; assumes object will not be nil.

Advanced Tip: Always break strong reference cycles in closures, delegates, and view controller hierarchies.


3. What is the difference between synchronous and asynchronous tasks in iOS?

Answer:

  • Synchronous: Blocks the current thread; can freeze UI.

  • Asynchronous: Runs in background, allowing the main thread to stay responsive.

  • Implementation: Use GCD (DispatchQueue) or OperationQueue for asynchronous execution.


4. Explain the differences between struct and class in Swift

Feature Struct Class
Type Value type Reference type
Inheritance Not supported Supported
Memory Stack Heap
Mutability var required Can modify even in let
Deinitializers Not supported Supported

Advanced Tip: Use structs for thread safety and immutability; use classes for shared mutable state.


5. What is the difference between weak, unowned, and strong references?

  • Strong: Keeps object alive; default.

  • Weak: Prevents retain cycles; automatically becomes nil if object deallocated.

  • Unowned: Prevents retain cycles; assumes object exists; crashes if nil.

Example in closures:

class ViewController {
    var closure: (() -> Void)?
    
    func setup() {
        closure = { [weak self] in
            self?.doSomething()
        }
    }
}

6. Explain MVVM architecture in iOS

Answer:

  • Model: Handles business logic and data.

  • View: UI components; only handles display.

  • ViewModel: Connects Model and View; processes data for the view.

Advantages over MVC:

  • Reduces massive view controllers.

  • Improves testability.

  • Supports reactive programming with Combine or RxSwift.


7. What is Core Data and how do you optimize it?

Answer:

  • Core Data is Apple’s object graph and persistence framework.

  • Stores data in SQLite or in-memory stores.

Optimization Tips:

  • Use fetch limits and batch size to reduce memory.

  • Avoid fetched properties for large datasets.

  • Use NSFetchedResultsController for table/collection view syncing.

  • Use background contexts for heavy operations.


8. Explain Grand Central Dispatch (GCD) and its queues

Answer:

  • GCD: Framework for concurrent code execution.

  • Queues:

    • Main Queue: Serial; updates UI.

    • Global Queue: Concurrent; background tasks.

    • Custom Queue: Serial or concurrent for specific tasks.

Example:

DispatchQueue.global(qos: .background).async {
    // background task
    DispatchQueue.main.async {
        // update UI
    }
}

9. What are Swift Optionals and how do you handle them safely?

  • Optionals represent a value or nil.

  • Safe handling techniques:

    • Optional binding (if let, guard let)

    • Nil coalescing operator (??)

    • Optional chaining (object?.property)

    • Force unwrapping (!) – avoid in production

Example:

let name: String? = "Yash"
print(name ?? "No name")

10. Explain Combine framework and its use

Answer:

  • Combine is Apple’s reactive programming framework introduced in iOS 13.

  • Handles asynchronous events using publishers and subscribers.

Example:

import Combine

let publisher = [1,2,3].publisher
let subscriber = publisher.sink { value in
    print(value)
}
  • Use Combine for network calls, UI updates, and state management.


11. How do you optimize iOS app performance?

  • Reduce unnecessary layout calculations.

  • Avoid heavy main thread operations.

  • Use lazy loading for images and data.

  • Cache resources using NSCache.

  • Profile using Instruments: CPU, Memory, and Time Profiler.


12. Explain URLSession and networking in iOS

  • URLSession: Framework for making HTTP requests.

  • Supports data tasks, download tasks, and upload tasks.

  • Use background sessions for large downloads.

  • Always perform JSON decoding asynchronously.

Example:

let url = URL(string: "https://api.example.com")!
URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data else { return }
    let json = try? JSONSerialization.jsonObject(with: data)
}.resume()

13. How do you prevent memory leaks in iOS?

  • Avoid strong reference cycles in closures, delegates, and view controllers.

  • Use weak/unowned references appropriately.

  • Monitor memory using Instruments (Leaks, Allocations).

  • Release unused objects and cached resources.


14. Explain SwiftUI and its advantages

  • SwiftUI is Apple’s declarative UI framework introduced in iOS 13.

  • Advantages:

    • Less boilerplate code than UIKit

    • Live previews in Xcode

    • Cross-platform (iOS, macOS, watchOS, tvOS)

    • Supports state management using @State, @Binding, @ObservedObject

Example:

struct ContentView: View {
    @State private var counter = 0
    
    var body: some View {
        Button("Tap \(counter)") {
            counter += 1
        }
    }
}

15. How do you handle background tasks in iOS?

  • Use background modes in app capabilities (e.g., audio, location, fetch).

  • Use BackgroundTasks framework for deferred tasks in iOS 13+.

  • Perform heavy tasks in background threads using GCD or OperationQueue.


16. Explain Push Notifications and APNs

  • iOS apps use Apple Push Notification Service (APNs) to receive notifications.

  • Steps:

    1. App registers for push notifications.

    2. APNs sends device token.

    3. Server sends payload to APNs with device token.

    4. APNs delivers to device.

  • Can handle notifications foreground, background, and terminated states.


17. How do you handle data persistence in iOS?

  1. UserDefaults: Small key-value storage.

  2. Core Data: Object graph and database.

  3. Keychain: Secure data storage (passwords, tokens).

  4. File System: Saving files in Documents or Caches.

  5. Realm: Third-party database for faster object persistence.


18. What is the difference between @State, @Binding, @ObservedObject, and @EnvironmentObject in SwiftUI?

Property Wrapper Purpose
@State Local state of a view
@Binding Two-way binding with another view’s state
@ObservedObject Observes external class conforming to ObservableObject
@EnvironmentObject Shared state across multiple views

19. Explain difference between viewDidLoad, viewWillAppear, and viewDidAppear

  • viewDidLoad: Called once when view is loaded. Initialize data/UI.

  • viewWillAppear: Called every time before view appears. Update UI or animations.

  • viewDidAppear: Called after view appears. Start animations or tracking.


20. How do you handle app architecture for scalable iOS apps?

  • Use MVVM + Coordinator pattern to separate navigation from business logic.

  • Use Dependency Injection for better testability.

  • Use Combine/RxSwift for reactive UI updates.

  • Modularize features to separate frameworks and maintain codebase.


21. What is the Coordinator pattern in iOS?

Answer:

  • The Coordinator pattern is used to manage navigation and flow in an iOS app.

  • It separates navigation logic from ViewControllers, improving modularity and testability.

  • Each coordinator handles a feature or flow in the app.

Example:

class AppCoordinator {
    var navigationController: UINavigationController
    
    func start() {
        let homeVC = HomeViewController()
        homeVC.coordinator = self
        navigationController.pushViewController(homeVC, animated: true)
    }
    
    func goToDetails() {
        let detailsVC = DetailsViewController()
        navigationController.pushViewController(detailsVC, animated: true)
    }
}

22. What is the difference between OperationQueue and GCD?

Feature OperationQueue GCD (DispatchQueue)
Abstraction High-level, object-oriented Low-level C API
Dependencies Supports dependencies between operations No built-in dependencies
Cancellation Can cancel operations No built-in cancellation
Priorities Supports priorities QoS for queues

Use Case: Use OperationQueue when you need dependencies, priorities, or cancellation. Use GCD for simple concurrent tasks.


23. How do you prevent retain cycles in iOS?

  • Use weak references for delegates:

protocol Delegate: AnyObject {}
class MyClass {
    weak var delegate: Delegate?
}
  • Use [weak self] or [unowned self] in closures.

  • Avoid strong reference cycles in view controller hierarchies.

  • Monitor leaks using Xcode Instruments → Leaks.


24. Explain Core Data migration

  • Lightweight Migration: Automatic migration if small schema changes (add/remove attributes).

  • Heavyweight Migration: Manual migration for complex changes using mapping models.

  • Always test migration paths to avoid app crashes when updating data models.


25. How do you implement caching in iOS apps?

  • NSCache: In-memory cache for images or data, auto-purged under memory pressure.

  • URLCache: Cache network responses.

  • Disk Cache: Store large data on file system.

  • Third-party libraries: Kingfisher, SDWebImage for image caching.


26. Explain Swift property wrappers

  • Property wrappers add behavior to properties.

  • Common wrappers: @State, @Binding, @ObservedObject, @Published.

  • Custom example:

@propertyWrapper
struct Capitalized {
    private var value: String = ""
    var wrappedValue: String {
        get { value }
        set { value = newValue.capitalized }
    }
}

struct User {
    @Capitalized var name: String
}

27. What is the difference between @Published and @ObservedObject?

  • @Published marks a property inside a class conforming to ObservableObject to trigger UI updates.

  • @ObservedObject is used in a SwiftUI view to observe changes in the object.


28. How do you optimize UITableView or UICollectionView performance?

  • Reuse cells using dequeueReusableCell.

  • Avoid heavy layout calculations in cellForRow.

  • Use prefetching APIs for large datasets.

  • Cache images and async load them.

  • Avoid nested loops inside cell rendering.


29. What is the difference between background fetch and silent push notifications?

Feature Background Fetch Silent Push
Trigger iOS decides when to run Server triggers
Use Fetch small data periodically Update data in background
Limitations No guaranteed execution time Limited execution time
Requires Background mode capability Push notification entitlement

30. Explain URLSession background tasks

  • Use URLSession(configuration: .background) for downloads/uploads that continue even when app is suspended or killed.

  • Requires delegate methods to handle completion, progress, and errors.

Example:

let config = URLSessionConfiguration.background(withIdentifier: "com.app.bg")
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)

31. How do you handle multithreading in iOS?

  • Use GCD for async tasks.

  • Use OperationQueue for dependencies and cancellations.

  • Always update UI on the main thread:

DispatchQueue.main.async {
    self.tableView.reloadData()
}

32. Explain the difference between Synchronous and Asynchronous Core Data operations

  • Synchronous: Main context performs operations on main thread (blocks UI).

  • Asynchronous: Use background context for heavy fetches or inserts to keep UI responsive.


33. Explain differences between weak, unowned, and strong in Swift with closures

  • Strong closure: Captures self strongly → retain cycle.

  • Weak closure: Optional self; avoids cycle, may be nil.

  • Unowned closure: Non-optional self; crashes if self deallocated.


34. Explain Swift Generics

  • Generics allow writing reusable and type-safe code.

  • Example:

func swapValues<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}
  • Widely used in Collections, Network Responses, and Custom Data Structures.


35. How do you handle error handling in Swift?

  • Throwing functions: func readFile() throws -> String

  • Do-Catch:

do {
    let result = try readFile()
} catch {
    print(error.localizedDescription)
}
  • Result type:

func fetchData() -> Result<Data, Error> {}

36. How do you implement deep linking in iOS apps?

  • Universal Links: Open specific content in the app using HTTP/HTTPS links.

  • Custom URL schemes: Open app with myapp://.

  • Update AppDelegate or SceneDelegate to handle URLs.


37. What is the difference between UIApplicationDelegate and SceneDelegate?

  • UIApplicationDelegate: Handles app-level events (launch, background, push notifications).

  • SceneDelegate: Introduced in iOS 13 to handle multiple UI scenes (multi-window support on iPad).


38. Explain differences between UIKit and SwiftUI

Feature UIKit SwiftUI
Paradigm Imperative Declarative
UI Updates Manual Automatic with state binding
Preview Only runtime Live previews in Xcode
Learning curve Established, extensive Newer, simpler syntax
Interoperability Easy to use Objective-C Can embed UIKit using UIViewRepresentable

39. How do you perform unit testing in iOS?

  • Use XCTest framework.

  • Test business logic, models, and network responses.

  • Use mocking for API calls or dependencies.

  • Use XCUITest for UI automation testing.


40. How do you monitor performance in iOS apps?

  • Instruments: CPU, Memory, Time Profiler, Leaks, Network.

  • Xcode Debug Navigator: Check memory usage, CPU, and disk.

  • Optimize:

    • Lazy loading

    • Efficient layouts

    • Background processing


41. Explain the difference between lazy var and computed properties in Swift

Feature Lazy Variable Computed Property
Initialization Initialized once when first accessed Calculated every time accessed
Storage Stores value in memory No storage; calculated on access
Use Case Heavy objects, deferred initialization Derived values, dynamic calculations
Mutability Can be modified if declared var Read-only or read-write depending on getter/setter

Example:

lazy var heavyObject = HeavyClass()
var computedValue: Int { return array.count * 2 }

42. What is Codable in Swift?

Answer:

  • Codable is a protocol used to encode and decode data for JSON, plist, or other formats.

  • Combines Encodable and Decodable protocols.

  • Simplifies parsing APIs without writing boilerplate code.

Example:

struct User: Codable {
    var name: String
    var age: Int
}
let jsonData = try JSONEncoder().encode(user)
let decodedUser = try JSONDecoder().decode(User.self, from: jsonData)

43. Explain the differences between NSManagedObjectContext types in Core Data

Context Type Description
Main Context Runs on main thread; use for UI updates
Background Context Runs on background thread; use for heavy fetches/inserts
Private Context Fully isolated; can merge changes with main context

Tip: Always save background contexts asynchronously to avoid blocking UI.


44. Explain the difference between weak, unowned, and strong in Swift

  • Strong: Keeps reference; default.

  • Weak: Optional, avoids retain cycles; auto nil when object deallocates.

  • Unowned: Non-optional; assumes object always exists; crashes if object is nil.

Example in closures:

closure = { [weak self] in self?.doSomething() }
closure = { [unowned self] in doSomething() }

45. How do you implement background tasks in iOS?

  1. Background Modes: Enable capabilities (audio, location, fetch).

  2. BackgroundTasks framework (iOS 13+): Schedule tasks for deferred execution.

  3. GCD/OperationQueue: Perform heavy tasks in background threads.

Example:

let task = BGAppRefreshTaskRequest(identifier: "com.app.refresh")
task.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
try BGTaskScheduler.shared.submit(task)

46. How do you implement animations in iOS?

  1. UIView Animations: Basic animations for properties.

UIView.animate(withDuration: 0.5) {
    view.alpha = 0.5
}
  1. Core Animation (CALayer): More control, keyframe and path animations.

  2. SwiftUI Animations: Declarative animations using .animation() and .withAnimation().

  3. Lottie Animations: Third-party library for JSON-based animations.


47. Explain DispatchGroup in GCD

  • Used to wait for multiple asynchronous tasks to complete.
    Example:

let group = DispatchGroup()

group.enter()
asyncTask1 { group.leave() }

group.enter()
asyncTask2 { group.leave() }

group.notify(queue: .main) {
    print("All tasks completed")
}

48. How do you optimize app launch performance?

  • Defer heavy work to background threads.

  • Lazy-load non-essential resources.

  • Use Static TableViews or SwiftUI Views for initial screen.

  • Preload assets asynchronously.

  • Profile using Time Profiler in Instruments.


49. What is the difference between viewDidLoad, viewWillAppear, viewDidAppear, viewWillDisappear, and viewDidDisappear?

Method When called Use Case
viewDidLoad Once when view is loaded Setup UI, initial data
viewWillAppear Every time view is about to appear Update UI, start animations
viewDidAppear After view appears Start timers, tracking
viewWillDisappear Before view disappears Save data, cancel tasks
viewDidDisappear After view disappears Release resources

50. Explain Push Notifications and silent notifications

  • Push Notifications: Notify user via APNs.

  • Silent Notifications: Trigger background updates without alerting the user.

  • Use Cases: Sync data, refresh content, background fetch.

  • Implementation: Handle in didReceiveRemoteNotification and configure content-available: 1 in payload.


51. Explain the differences between synchronous and asynchronous network requests

Feature Synchronous Asynchronous
Thread Blocking Blocks current thread Runs in background
UI Impact Freezes UI UI responsive
Usage Rare Recommended (URLSession)

Example with URLSession:

URLSession.shared.dataTask(with: url) { data, _, error in
    // Handle data asynchronously
}.resume()

52. How do you handle JSON parsing efficiently?

  • Use Codable for type-safe decoding/encoding.

  • Use JSONDecoder().keyDecodingStrategy to handle snake_case vs camelCase.

  • For large datasets, parse in background thread to avoid blocking UI.

Example:

DispatchQueue.global().async {
    let user = try? JSONDecoder().decode(User.self, from: data)
    DispatchQueue.main.async {
        self.updateUI(user)
    }
}

53. Explain Combine framework in iOS

  • Framework for reactive programming.

  • Handles asynchronous data streams and event-driven UI updates.

  • Key concepts: Publisher, Subscriber, Subject, Operators.

Example:

let publisher = [1, 2, 3].publisher
let subscriber = publisher.sink { value in
    print(value)
}
  • Combine is often used with MVVM to bind ViewModel to View.


54. Explain URLSession background sessions

  • Continue downloads/uploads even when app is suspended or terminated.

  • Must implement delegate methods to handle completion and progress.

let config = URLSessionConfiguration.background(withIdentifier: "com.app.bg")
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)

55. How do you secure sensitive data in iOS apps?

  1. Use Keychain for storing passwords and tokens.

  2. Avoid storing sensitive data in UserDefaults.

  3. Use HTTPS/SSL pinning for network requests.

  4. Enable App Transport Security (ATS).

  5. Obfuscate code if necessary to prevent reverse engineering.