iOS Flashcards
What is ARC?
Automatic reference counting:
- every instance in memory has a counter of the number of references to that instance.
- When the counter hits 0, then that instance can be safely removed from memory
- strong reference: when you have at least one pointer to an object
- weak reference: when there are no pointers to an object
What are the main differences between classes and structs in Swift?
Struct is value type (Stack); Class is reference type (Heap – slower in performance).
When you copy a struct, you end up with two unique copies of the data.
When you copy a class, you end up with two references to one instance of the data
Structs do not support inheritance but can adhere to protocols. Classes support inheritance.
What is the delegation pattern?
Delegation allows you to have one object delegate a task to another object. For example, having a viewcontroller provide the datasource for a UITableView
Explain MVC
Architecture approach that separates code into models, views, and controllers. Controllers generally handle the logic and act as an interface between the model and the view. Problem is with “massive view controllers”. For example if your view required date formatting, where should that formatting occur? Frequently dumped into the controller.
Explain MVVM
Model-view-viewmodel. Architecture approach that is similar to MVC but creates a viewModel layer for handling view logic. For example if your view required date formatting, then the viewmodel would be a good place for the date formatting to occur. This allows for lean view controllers and plays nice with reactive architectures, can setup all bindings in VC and then all logic happens in VM.
Explain Dependency Injection and give an example
DI is a pattern where we provide an object’s dependencies to it, instead of having this object seek out it’s dependencies. For example, if our VC needs a network service, then we can pass that networking object into the VC’s init. Benefits of this include: easier for testing, cleaner code, and less tightly coupled code.
What are the benefits of dependency injection?
- Better, more modular, testing
- Less tightly coupled code
- cleaner, easier to read
What is a retain cycle? Give an example
A retain cycle occurs when two objects are holding references to each other. Common example is when you reference self inside of a closure.
How to identify a retain cycle?
Use instruments tool or memory debug graph in xcode
Describe the view lifecycle
- viewDidLoad
- viewWillAppear
- viewWillLayoutSubviews
- viewDidLayoutSubviews
- viewDidAppear
- viewWillDisappear
- viewDidDisappear
Describe the different access modifiers
- public: can be called from any place within the module, or if the module is imported
- internal: can be called only from within the moudle
- file-private: can only be used within the file
- private: can only be used within the same declaration and it’s extensions
When do we need an escaping closure?
If the closure is called after the function is returned, like after a networking delay, it must be marked as escaping
How would you improve UITableView scroll performance?
- cell reuse
- pre-render the cell height
- cache images if possible
- avoid shadows, use rasterize to improve shadow performance
What is GCD?
low level api that allows users to run concurrent tasks, multithreading
Describe the different app states
- Not Running: The app has not been launched or it has been terminated.
- Inactive: The app is in the foreground but not receiving events, Ex. User has locked the device with the app active.
- Active: The normal state of “In Use” for an app.
- Background: The app is no longer on-screen, but still executing the code.
- Suspended: The app is still resident in memory but is not executing code.
If the user were to scroll really quickly, what would happen in the cells? Would they all show the correct image?
- In prepareForReuse set cell’s image to nil
- Might mention cancelling the network fetch
- Might mention checking the image url that was fetched against the one the cell is expecting to prevent populating the cell with the wrong image
Which thread must UI work be done on?
Main
What is a memory leak?
When an object that should be deallocated, has not been deallocated
How would you describe the swift language?
type-safe, can be used for scripting, or programming, across mobile, desktop, and sever. Can leverage protocols, and reactive functional paradigms
When would you use a DispatchGroup?
Dispatch groups are good for when we want to perform more than 1 time consuming operations before proceeding with some logic. For example, if we need to make multiple different requests to build a model, we can group those requests to simplify the order of events
What are locks in regards to GCD?
Locks prevent race conditions by requiring that a thread have a lock to access a piece of code. Threads w/o the lock cannot access that code.
What design patterns are you familiar with?
- MVC
- MVVM
- Coordinator
- Delegate pattern
- Factory pattern
- VIPER
- dependency injection / inversion
Explain the diff between strong and weak pointers
- strong reference increases the retain count of an object by 1
- weak reference is a pointer that does not increase the retain count
https://www.appypie.com/weak-vs-strong-references-swift
Why do we use weak references? Give some examples
- prevent retain cycles where two objects are pointing at each other
- examples:
- delegate properties: w/ tableview, we don’t want a tableVC to hold a strong reference to it’s datasource, otherwise we would get a retain cycle
- closures: closures can outlive the scope that they’re declared in. Use [weak self]
https://www.appypie.com/weak-vs-strong-references-swift
Explain the difference between weak and unowned?
- Weak: You use weak to create a weak reference to an object. This will automatically make that instance optional inside the closure.
- Unowned: Same as weak, except that the referenced instance is not an optional. You use this when you’re certain the instance cannot become nil.
https: //www.appypie.com/weak-vs-strong-references-swift
When are instances deallocated in ARC?
When the retain count hits 0
https://www.appypie.com/weak-vs-strong-references-swift
How would you manage a reference to self in a closure?
Use a capture list such as [weak self]
https://www.appypie.com/weak-vs-strong-references-swift
Are structs stored in the stack or heap?
Structs are stored in the stack
https://stackoverflow.com/questions/54549033/are-swift-structs-always-stored-in-the-stack
Are classes stored in the stack or heap?
Classes are stored in the heap
https://stackoverflow.com/questions/54549033/are-swift-structs-always-stored-in-the-stack
Why would someone choose a struct over a class?
- structs are copiable and potentially safer than having many pointers modifying it. important when passing around data
- less likely to have retain cycles bc struct is value type not reference
What is the memory debug graph?
Allows user to identify memory leaks inside of xcode. Good for spotting retain cycles
Define: concurrency
Doing multiple tasks at once
Define: thread
a “lane” for tasks to occur
What kind of operations should happen on the main thread?
UI / animations
What APIs can you use to manage concurrency and threading?
NSOperationQueue and GrandCentralDispatch
Name two types of queues
- serial queue
- concurrent queue
Explain a serial queue
- Tasks are executed in order, the second task does not begin until the first task is completed
Explain how a concurrent queue works
Tasks begin in order, but can complete out of order
What are the benefits of using a serial queue?
- predictable execution order
- prevents race conditions
What are the benefits of a concurrent queue?
- faster than serial queue
Is the main thread a serial or concurrent queue?
serial
Is a background thread serial or concurrent?
concurrent
What’s the problem with concurrent queues?
Race conditions, unpredictable completions
Describe the Public access modifier
Makes an object available to any other object in the module, or if the module is imported
Describe the Private access modifier
Makes an object available only to the enclosing declaration and it’s extensions
Describe the file-private access modifier
Restricts object access to a file
When would you use a private access modifier? Give an example
Use a private access modifier when you want to hide implementation details. For example, you have a price calculator, instead of exposing all of the calculations to other classes, maybe you set the calculations to private but set the getPrice() func to be public
Describe the internal access modifier?
Object can be used within source module, but not outside
What is a closure?
a block of code that you can store in a variable and pass around
What is an escaping closure?
a closure that completes after the function that it was passed to returns. For example, dataTaskWithURL
What is a non-escaping closure?
A closure that’s called within the function its passed to, before the function returns
Explain the difference between bounds and frame?
frame: position of a view to it’s superview, top-left of view is x,y
bounds: positions inside of the view, top-left of view is 0,0
What does a protocol extension allow us to do?
Allows us to create some optional protocol requirements
Explain the diff between == and ===
=== compares references pointers == compares equatable values
What is the nil coalescing operator?
provides a default value when unwrapping: ??
What are your options for persisting data on iOS?
- coredata
- user defaults
- keychain
- icloud
- sqlite
How would you implement debouncing on a search bar that returns live results?
- rxswift: cancel old requests when a new request happens
- could delay firing the request for a second
- GCD: DispatchWorkItem.cancel()
What is a race condition?
When more than one thread attempts to modify a value at the same time
What is a deadlock?
two threads are waiting for each other to finish, inifinitely
Give an example of when you would use generics
You could use generics to allow a function to accept multiple types as an input
Ways that a function can indicate an error
- throw
- return result
- return an optional
CompactMap vs Map vs FlatMap
- map: converts A to B
- compactMap: same as map but excludes nil, optionals
- flatMap: flattens an array of arrays into one array
What does Reduce do in Swift?
Combines elements of an array in a specified manner, ie get the total letter count of all strings in an array
What do you like about Swift?
- strong type safety
- readability, verbose
- functional reactive programming, swiftUI
What dont you like about Swift?
sometimes i feel overhwelmed with the velocity that new features are released, and it’s unclear to me what the future of Swift looks like. For example, Swift now has both the Combine framework and the async/await api to handle asynchronous events. To me those feel like competing tools and I guess i worry about which tool to invest myself in
What do you like about iOS?
“It just works”
What dont you like about iOS?
Xcode bugs. One version broke swiping back navigation tabs
Why is Swift considered strongly typed?
The compiler enforces typing. You cant add an Int to a String array
Define method swizzling
Change the implementation of a function at runtime so it behaves differently. Literally swapping function signatures.
Define the “not running” app state
The app has not been launched or it has been terminated.
Define the “Inactive” app state
The app is in the foreground but not receiving events, Ex. User has locked the device with the app active.
Define the “active” app state
The normal state of “In Use” for an app.
Define the “Background” app state
The app is no longer on-screen, but still executing the code.
Define the “Suspended” app state
The app is still resident in memory but is not executing code. ie answering a phone call
What state is your app in when interrupted to answer a phone call?
Suspended
What state describes the app when it’s in the foreground but there are no events firing?
inactive
What state describes when the app is terminated?
not running
What state describes when the app is running but not on screeN?
background
Difference between Delegate pattern and KVO / NSNotificationCenter
Delegate pattern is 1:1 relationship, KVO+NSNotificationCenter are 1:Many
What’s the difference between CoreData and SQLite database?
CoreData is object graph, SQLite is relational db
What db pattern does CoreData use? ie relational
object graph
What is MVVM good for?
- preventing massive VC
- separation of concerns
- good for testing
- good for reactive paradigms
- good for dependency injection
Is Swift an object-oriented language or a functional language?
Swift is a hybrid language that supports both paradigms.
Are closures value or reference types?
Closures are reference types. If a closure is assigned to a variable and the variable is copied into another variable, a reference to the same closure and its capture list is also copied.
What considerations do you need when writing a UITableViewController which shows images downloaded from a remote server?
- Only download the image when the cell is scrolled into view, 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.
- cache the images
- use placeholder images
- clear images in prepareForReuse
What is a protocol? Give an example?
A protocol is a tool for requiring an object to implement a set of functions. A common use is requiring a viewcontroller to conform to UITableViewDelegate
What is @escaping?
Tells the compiler that its ok for this closure to outlive the rest of the function
Define closures
Closures are self contained blocks of code that can be stored and passed