├── Screenshot
└── emum_Example.gif
└── README.md
/Screenshot/emum_Example.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carterTsai95/InterviewQuestion/HEAD/Screenshot/emum_Example.gif
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # iOS Developer Interview Preparation
2 |
3 | ## Purpose of this
4 |
5 | This idea come out when I start to prepare my iOS interview question. In this open source repository, I am trying to gather the related iOS interview question as much as I can. Then, I will use my own word to define/answer those of the question in order to examine my knowledge. I also recommend some book or resouce that I have read to prepare my interview, and I list below.
6 | - 100 Questions and Answers to Help You Land Your Dream iOS Job: Or to Hire the Right Candidate!
7 | - [Top 50 Swift Interview Questions](https://www.softwaretestinghelp.com/swift-interview-questions/)
8 | - [Swift Interview Questions and Answers - Raywenderlich](https://www.raywenderlich.com/762435-swift-interview-questions-and-answers)
9 | - [Hacking with the Swift - Over 150 iOS interview questions](https://www.hackingwithswift.com/interview-questions)
10 |
11 | ## Table of Contents
12 |
13 | - [Swift Fundemantal Knowledge](https://github.com/tsaihong1995/InterviewQuestion#swift-fundemantal-knowledge)
14 |
15 | - [What are struct and class in iOS? What is the difference? When would you use each?](https://github.com/tsaihong1995/InterviewQuestion#what-are-struct-and-class-in-ios-what-is-the-difference-when-would-you-use-each)
16 | - [What is framework in iOS? & What iOS frameworks do you have experience working with?](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#what-is-framework-in-ios)
17 | - [How can you store information within your iOS app?](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#how-can-you-store-information-within-your-ios-app)
18 | - [How do you cast between types?](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#how-do-you-cast-between-types)
19 | - [What is the difference between var and let?](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#what-is-the-difference-between-var-and-let)
20 | - [What is the difference between implicit and explicit?](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#what-is-the-difference-between-implicit-and-explicit)
21 | - [Tell me about enum in Swift language. Can you give useful examples of enum associated values?](https://github.com/tsaihong1995/InterviewQuestion#tell-me-about-enum-in-swift-language-can-you-give-useful-examples-of-enum-associated-values)
22 | - [What is Core Data?](https://github.com/tsaihong1995/InterviewQuestion#what-is-core-data)
23 | - [When would you use Core Data over NSUserDefault?](https://github.com/tsaihong1995/InterviewQuestion#when-would-you-use-core-data-over-nsuserdefault)
24 | - [What is NSFetchRequest?](https://github.com/tsaihong1995/InterviewQuestion#what-is-nsfetchrequest)
25 |
26 | - [Debugging & Optimization](https://github.com/tsaihong1995/InterviewQuestion#debugging)
27 | - [How do you debug and profile code on iOS application?](https://github.com/tsaihong1995/InterviewQuestion#how-do-you-debug-and-profile-code-on-ios-application)
28 | - [How do you optimize scrolling performance of dynamically sized table or collection views?](https://github.com/tsaihong1995/InterviewQuestion#how-do-you-optimize-scrolling-performance-of-dynamically-sized-table-or-collection-views)
29 | - [Explain your process for tracing and fixing memory leaks.](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#explain-your-process-for-tracing-and-fixing-memory-leaks)
30 | - [You’ve just been alerted that your new app is prone to crashing. What do you do?](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#youve-just-been-alerted-that-your-new-app-is-prone-to-crashing-what-do-you-do)
31 | - How do you test your code? How do you make your code testable? (Todo)
32 |
33 | - [Design Pattern](https://github.com/tsaihong1995/InterviewQuestion#design-patterns)
34 | - [What is Singleton Pattern?](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#what-is-singleton-pattern)
35 | - [What is the delegation pattern? How would you explain delegates to a new Swift developer?](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#what-is-the-delegation-pattern)
36 | - [What is MVC?](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#what-is-mvc)
37 | - [What is MVVM?](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#what-is-mvvm)
38 |
39 | - [General / Uncategorized](https://github.com/tsaihong1995/InterviewQuestion#general--uncategorized)
40 |
41 | - [What is a protocol? How do you define your own protocol?](https://github.com/tsaihong1995/InterviewQuestion#what-is-a-protocol-how-do-you-define-your-own-protocol)
42 | - [What is the difference between a class and an object?](https://github.com/tsaihong1995/InterviewQuestion#what-is-json-what-are-the-pros-and-cons)
43 | - [What is JSON? What are the pros and cons?](https://github.com/tsaihong1995/InterviewQuestion#what-is-json-what-are-the-pros-and-cons)
44 | - [What is the difference between not-running, inactive, active, background and suspended execution states?](https://github.com/tsaihong1995/InterviewQuestion#what-is-the-difference-between-not-running-inactive-active-background-and-suspended-execution-states)
45 | - [What is KVO?](https://github.com/tsaihong1995/InterviewQuestion#what-is-kvo)
46 | - [What is NSFetchRequest?](https://github.com/tsaihong1995/InterviewQuestion#what-is-nsfetchrequest)
47 |
48 | - [Memory Management](https://github.com/tsaihong1995/InterviewQuestion#memory-management)
49 | - [Why do you generally create a weak reference when using self in a block?](https://github.com/tsaihong1995/InterviewQuestion#why-do-you-generally-create-a-weak-reference-when-using-self-in-a-block)
50 | - [What is memory management handled on iOS?](https://github.com/tsaihong1995/InterviewQuestion#what-is-memory-management-handled-on-ios)
51 | - [What is the difference between *weak* and *strong*?](https://github.com/tsaihong1995/InterviewQuestion#what-is-the-difference-between-weak-and-strong)
52 | - [What is a memory leak?](https://github.com/tsaihong1995/InterviewQuestion#what-is-a-memory-leak)
53 | - [What is a retain cycle?](https://github.com/tsaihong1995/InterviewQuestion#what-is-a-retain-cycle)
54 | - [What is the difference between copy and retain?](https://github.com/tsaihong1995/InterviewQuestion#what-is-the-difference-between-copy-and-retain)
55 | - [What is the difference between a stack vs a heap?](https://github.com/tsaihong1995/InterviewQuestion#what-is-the-difference-between-a-stack-vs-a-heap)
56 | - [What are “strong” and “weak” references? Why are they important and how can they be used to help control memory management and avoid memory leaks?](https://github.com/tsaihong1995/InterviewQuestion/blob/main/README.md#what-are-strong-and-weak-references-why-are-they-important-and-how-can-they-be-used-to-help-control-memory-management-and-avoid-memory-leaks)
57 |
58 | - [Thread Management](https://github.com/tsaihong1995/InterviewQuestion#thread-management)
59 | - [What is the difference between synchronous and asynchronous task?](https://github.com/tsaihong1995/InterviewQuestion#what-is-the-difference-between-synchronous-and-asynchronous-task)
60 | - [What is GCD and how is it used?](https://github.com/tsaihong1995/InterviewQuestion#what-is-gcd-and-how-is-it-used)
61 |
62 |
63 | # Interview Questions & Answers
64 |
65 |
66 | ## Swift Fundemantal Knowledge
67 |
68 | ### What are struct and class in iOS? What is the difference? When would you use each?
69 |
70 | The common parts between struct and class:
71 | - Both can define properties and functions in classes/structs
72 | - Both can has initializers to initialize thier original state with init()
73 | - Can use **extension** to extended the functionality
74 | - Both can conform to protocols.
75 |
76 |
77 | The stuct is ***Value*** type. In Swift, the struct type will be passed as values rather than references which means value type is an independent instance and holds its data in its own memory allocation. One of the Pros is if there is a large object it needs to pass around. Using structs can improve the performance.
78 |
79 | In Swift **struct**, **Array**, **String**, **Dictionary**, **tuple** are value types.
80 |
81 | Structs are preferable to use if
82 | - It doesn't have to inherit value from other types.
83 | - When programmer only want to encapsulate some data.
84 |
85 |
86 | Struct Example
87 |
88 | ```swift
89 | struct Bike {
90 | let brand: String
91 | var model: String
92 | }
93 |
94 | var bike1 = Bike(brand: "Giant", model: "G-1")
95 |
96 | let bike2 = bike1
97 |
98 | bike1.model = "G-2"
99 |
100 | print(bike1)
101 | print(bike2)
102 |
103 | /*
104 | Output:
105 | Bike(brand: "Giant", model: "G-2")
106 | Bike(brand: "Giant", model: "G-1")
107 |
108 | Note: Only Bike1's model has changed.
109 | */
110 | ```
111 |
112 |
113 |
114 | The ***class*** is reference types which stored on heap. The class also has ability:
115 | - Inheritance from the other class.
116 | - Classes can be deinitialized.
117 |
118 |
119 | Class Example
120 |
121 | ```swift
122 | class Person: CustomStringConvertible {
123 | var age: Int
124 | var name: String
125 |
126 | var description: String {
127 | return "Age \(age) - Name \(name)"
128 | }
129 |
130 | init(age: Int, name: String) {
131 | self.age = age
132 | self.name = name
133 | }
134 | }
135 |
136 |
137 | let person1 = Person(age: 20, name: "Hung-Chun")
138 |
139 | let person2 = person1
140 |
141 | person2.age = 18
142 |
143 | person1.name = "Carter"
144 |
145 | print(person1)
146 | print(person2)
147 |
148 | /*
149 | Output:
150 | Age 18 - Name Carter
151 | Age 18 - Name Carter
152 |
153 | Note: Because class is reference type, when we assign the person2 = person1, we indicate that person2 point to the person1's address. So when we modify the person1 or 2's property value, it will modify both's.
154 | */
155 |
156 |
157 |
158 | ```
159 |
160 |
161 |
162 |
163 | ### What is framework in iOS?
164 |
165 | The framework in iOS is like the container with the various resources (images, data files, UI objects, etc.) Framework also can be library or containing many libraries, collection of scripts.
166 |
167 |
168 | ### How can you store information within your iOS app?
169 |
170 | There are many different ways that we can achieve data persistence in Swift
171 | - **UserDefault**
172 | UserDefault usually store small amount of user's data like (settings, preferences, etc.)
173 | -Limitation :
174 | - UserDefault is not encrypted
175 | - Unit testing user defaults can occur some false positives.
176 | - **Keychain**
177 | It usually use to save the sensitive user data. For example: Password, login information...
178 | -Pros:
179 | - Thread safety
180 | - All information in keychain is encrypted
181 |
182 | - **Saving file to disk**
183 | We can also encode the data to the JSON file then save it to the user's local device. When the application is running or execute, it will read/write the data from the path.
184 |
185 | - **Core Data**
186 | Core Data is Apple's persistency framework which based on an object graph. It can uss for saving the app's permanet data for offline use or cache the data.
187 | - **SQLite**
188 |
189 | ### How do you cast between types?
190 |
191 | > Apple - A constant or variable of a certain class type may actually refer to an instance of a subclass behind the scenes. Where you believe this is the case, you can try to downcast to the subclass type with a type cast operator (as? or as!).
192 |
193 | Downcasting can be done in two ways:
194 | - Conditional downcasting (as?).
195 | - Forced downcasting (as!)
196 |
197 | Conditional Downcasting
198 | While using the conditional downcasting, it will always return an optional value. That's mean when the downcasting is not available, it will always return _nil_.
199 |
200 | Forced Downcasting
201 | When we use the Forced Downcasting, we need to make sure that the downcast will always succeed. Otherwise, it will occure runtime error if we try to downcast to an unvailable class type.
202 |
203 | Upcasting can lets the base class object to cast to its superclass.
204 |
205 | ```swift
206 | class PizzaStore {
207 | var establish :Int?
208 |
209 | init(establish:Int?) {
210 | if let establish = establish {
211 | self.establish = establish
212 | }
213 | }
214 | }
215 |
216 | class Dominos: PizzaStore {
217 | var name: String?
218 |
219 | init(name:String?, establish:Int?) {
220 | if let name = name {
221 | self.name = name
222 | }
223 | super.init(establish: establish ?? 0)
224 | }
225 | }
226 |
227 | class PizzaHut: PizzaStore {
228 | var hasApplePie: Bool?
229 |
230 | init(hasApplePie:Bool?, establish:Int?) {
231 | if let hasApplePie = hasApplePie {
232 | self.hasApplePie = hasApplePie
233 | }
234 | super.init(establish: establish ?? 0)
235 | }
236 | }
237 |
238 | let pizzaStoreArray = [Dominos(name: "Domino's", establish: 1960), PizzaHut(hasApplePie: false, establish: 1958)]
239 |
240 | let dominoPizzaStore = pizzaStoreArray[0] as! Dominos
241 | let dominoPizzaStoreAsPizzaStore = dominoPizzaStore as PizzaStore
242 | ```
243 |
244 |
245 | ### What is the difference between var and let?
246 |
247 | The **let** keyword defines a constant which means the property that we don't want it to change their value.
248 |
249 | > Note: The optional and the weak can't be written using let.
250 |
251 | The **var** defines a variable which can let us to modify it's value.
252 |
253 | ### What is the difference between implicit and explicit?
254 |
255 | When referring to something as implicit or explicit, it is often referring to how an object is declared. In the two examples below:
256 |
257 |
258 | Swift
259 |
260 | ```swift
261 | var name: String = "onthecodepath" // explicit
262 | var name = "onthecodepath" // implicit
263 | ```
264 |
265 |
266 | In the first line above, the name variable is *explicitly* declared since the type of the variable follows the name of the variable. In the second line, the String type is not explicitly declared. However, Swift is able to infer that name is of a String type since the value that it is being set as is of a String type.
267 |
268 | ### Tell me about enum in Swift language. Can you give useful examples of enum associated values?
269 |
270 | An enumeration (enum) is value type in a type-safe way. It is not mandotary to provide the initial value for the enumeration.
271 |
272 | Here’s an example for the four main points of a compass:
273 |
274 | ```swift
275 | enum Direction {
276 | case north
277 | case south
278 | case east
279 | case west
280 | }
281 | ```
282 |
283 | > Note: Swift enums don’t have integer values set by default. In example above north, south, east, west don’t implicitly equal 0 ,1 ,2 ,3. Instead these enumeration cases are values in their own right of type _Direction_.
284 |
285 | **Important**: A swich statement must be exhaustive if we want to use the enumeration in it. If we use the _default_, it is not nessasary to include all the cases.
286 |
287 | ```swift
288 | let someAnimal = Animal.human
289 | switch somePlanet {
290 | case .human:
291 | print("This is human species")
292 | default:
293 | print("The animal is other than human")
294 | //It is no need to include all the cases in the Animal enumeration.
295 | }
296 | // Prints "The animal is other than human"
297 | ```
298 |
299 | - Associate values lets us add more information to our enumeration.
300 |
301 | The scenario is "In my SwiftUI application, I want to present different views modal, when I selected the certain button." In this case, we can use the enum associate value helps us to tackle down this problem.
302 |
303 | Requirement:
304 | 1. We have 3 different view we want to provide to user to select
305 | - Home View
306 | - Favorite View
307 | - Setting View
308 |
309 | Step 1. Let us define the MyOption which will contain those three views
310 |
311 | ```swift
312 |
313 | //We want to present the implicitly our each view name, so we need to conform to String and CaseIterable.
314 |
315 | enum UserOption: String, CaseIterable {
316 | case setting = "Setting View"
317 | case action1 = "Action 1"
318 | case action1 = "Action 2"
319 | }
320 | ```
321 | Step 2. Let's wrap the UserOption enum into the other enum because we will use the function to determine which case user is selected and generate the corresponding view.
322 |
323 | ```swift
324 | enum OtherViews {
325 | enum UserOption: String, CaseIterable {
326 | case setting = "Setting View"
327 | case action1 = "Action 1"
328 | case action2 = "Action 2"
329 | }
330 |
331 | static func optionView(optionSelected: UserOption) -> AnyView {
332 | switch optionSelected {
333 | case .setting:
334 | return AnyView(Text("Showing Setting View"))
335 | case .action1:
336 | return AnyView(Text("Showing Action1 View"))
337 | case .action2:
338 | return AnyView(Text("Showing Action2 View"))
339 | }
340 |
341 | }
342 | }
343 | ```
344 |
345 | Step 3. Let create our view to include those fucntionality.
346 |
347 | ```swift
348 | import SwiftUI
349 |
350 | struct ContentView: View {
351 | @State private var isShowingModal = false
352 | @State private var optionSelected: OtherViews.UserOption = .action1
353 | var body: some View {
354 | VStack {
355 | Picker(selection: $optionSelected, label: Text("")) {
356 |
357 | ForEach(OtherViews.UserOption.allCases, id: \.self) { option in
358 | Text(option.rawValue.capitalized).tag(option)
359 |
360 | }
361 | }.pickerStyle(SegmentedPickerStyle())
362 | Button("Show Modal") {
363 | self.isShowingModal.toggle()
364 | }
365 | .sheet(isPresented: $isShowingModal) {
366 | OtherViews.optionView(optionSelected: optionSelected)
367 | }
368 | }
369 | .padding()
370 | }
371 | }
372 |
373 | struct ContentView_Previews: PreviewProvider {
374 | static var previews: some View {
375 | ContentView()
376 | }
377 |
378 | }
379 | ```
380 |
381 |
382 |
383 | ### What is Core Data?
384 |
385 | Core Data is a framework that is used to manage model layer objects (Like the M in MVC). It has the ability to persist object graphs to a persistent store. Data is organized into relational entity-attribute model.
386 |
387 | #### When would you use Core Data over NSUserDefault?
388 |
389 | - Most of time, NSUserDefault is used to store small quantity of data (settings, preferences, etc.). The UserDefault object known as NSUserDefault.
390 | - Core Data is used to store a large amount of data.
391 |
392 |
393 | ### What is NSFetchRequest?
394 |
395 | NSFetchRequest is the class responsible for fetching from Core Data. Fetch requests can be used to fetch a set of objects meeting a certain criteria, individual values and more. ([source](https://medium.com/ios-os-x-development/50-ios-interview-questions-and-answers-part-2-45f952230b9f))
396 |
397 | ## Debugging
398 |
399 | ### How do you debug and profile code on iOS application?
400 | - Using NSLog and print functions can be used for output into console.
401 | - Set the breakpoints and using the Debug bar and Variables view to monitor the object or class.
402 | - Some Senior Developer will use the Crash Logs to gain more information and try to find out the specific problem.
403 |
404 | ### How do you optimize scrolling performance of dynamically sized table or collection views?
405 |
406 | Firstly, I will analyze which element or reason cause the choppy loading while using the collection views. Most of the time it is because we load the data (Image, text, object) synchronously.
407 |
408 | Imangine this scenario in the restaurant. In the restarant there are 3 chief but only have one server. The customer order the bunch of the dishes (Just like user scrolling down the collection view). Sometime the kitchen (backend) might able to handle this big volume, but we only open one thread to serve our content which is data.
409 |
410 | So we might can do following strategies to improve the performence.
411 | - **Splitting out the long-running operations and move them to a background thread.**
412 | This allows us to handle any events when they happen, on the main thread. When the background operation completes, you can make any required UI updates, based on the operation, on the main thread.
413 | - **Loading the data asynchronously **
414 | We can use Grand Central Dispatch (GCD) to execute tasks concurrently. The main idea is to create a closure to handle how the cell is updated once the data is loaded.
415 | - **Prefetching the data**
416 | The problem occur while we fetch big amount of the data. But we also can try to prefethching the oncoming data. For example, the view only present the data 1-10, meanwhile we let our program already fetch the next 11-20 and 21-30 items. Whenever the user scroll down, we continually fetching the oncoming data.
417 |
418 | ### Explain your process for tracing and fixing memory leaks.
419 |
420 | I will use the Memory Graph Debugger and try to find out which object causing the memory leak.
421 |
422 | Some step I will reaptly do:
423 | - Execute the core/main functionality of the application serveral times.
424 | - Take the memory snapshot and observe how many instance it exist for each object.
425 | - If I found out there has instance shouldn't existing in the memory anymore, it might be the object which causing the memory leak.
426 | - Try to track down it's parent node and analyze the code which lead the strong reference coming.
427 |
428 | ### You’ve just been alerted that your new app is prone to crashing. What do you do?
429 |
430 | There are some steps that I will attemp.
431 | - If the user willing to sent their device model, iOS version it will be a big help. Try to indicate whether certain model or version of iOS cause this crashing.
432 | - If it is possible, try to reproduce the error and using different simulator to find out the issue.
433 | - If it's possible, request the user to provide the detail of which action cause the crashing/error.
434 |
435 |
436 | ## Design Patterns
437 |
438 | ### What is Singleton Pattern?
439 |
440 | 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. ([source](https://medium.com/ios-os-x-development/ios-interview-questions-13840247a57a))
441 |
442 | ### What is the delegation pattern?
443 |
444 | The delegation pattern is a powerful pattern used in building iOS applications. The basic idea is like the *delegate* the mission/task to the worker. One object will act on another object's behalf or in coordination with another object.
445 |
446 | In this scenario, the 'PizzaStore' in charge of assigning task to worker, and 'PizzaStore' delegate making the pizza dough to 'Worker'. Once worker done then give the baked pizza to manager, so PizzaStore can get the pizza.
447 |
448 | ```swift
449 | import SwiftUI
450 |
451 | struct ContentView: View {
452 | struct Pizza {
453 | var size:Int = 15
454 | }
455 |
456 | protocol PizzaStoreDelegate {
457 | func pizzaWasBaked(_ pizza: Pizza)
458 | }
459 |
460 | class PizzaStore
461 | {
462 | var delegate:PizzaStoreDelegate?
463 |
464 | func makePizza()
465 | {
466 | var pizza = Pizza()
467 | pizza.size = 6
468 |
469 | delegate?.pizzaWasBaked(pizza)
470 | }
471 | }
472 |
473 | class Worker: PizzaStoreDelegate
474 | {
475 | func pizzaWasBaked(_ pizza: Pizza) {
476 | print("The worker start produce the pizza")
477 | print("The pizza has baked by worker")
478 | }
479 | }
480 |
481 | let worker = Worker()
482 |
483 | let pizzaStore = PizzaStore()
484 |
485 | pizzaStore.delegate = worker
486 | pizzaStore.makePizza()
487 |
488 | /*
489 | Output:
490 | The worker start produce the pizza
491 | The pizza has baked by worker
492 | */
493 |
494 | ```
495 |
496 |
497 |
498 |
499 |
500 | ### What is MVC?
501 |
502 | MVC stands for **Model-View-Controller**. It is a software architecture pattern for implementing user interfaces.
503 |
504 | MVC consists of three layers: the model, the view, and the controller.
505 | - The **model layer** is typically where the data resides (persistence, model objects, etc)
506 | - 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.
507 | - The **controller (view controller)** is the layer that integrates the view layer and the model layer together.
508 |
509 | ### What is MVVM?
510 |
511 | MVVM stands for **Model-View-ViewModel**. It is a software architecture pattern for implementing user interfaces.
512 |
513 | MVVM is an augmented version of MVC where the presentation logic is moved out of the controller and into the view model. The view model is responsible for handling most, if not all, of the view's display logic.
514 |
515 | A common occurence in MVC is where you have a massive-view-controller (some joke this is what MVC stands for). In order to shrink the size of your view controller and make the logic and readibility of your code easier to follow along, the MVVM will be used.
516 |
517 | ## General / Uncategorized
518 |
519 | ### What considerations do you need when writing a UITableViewController which shows images downloaded from a remote server?
520 |
521 | - Only download the image when the cell is scrolled into view (when cellForRowAtIndexPath is called)
522 | - Download the image asynchronously on a background thread so as not to block the UI so the user can keep scrolling
523 | - When the image has downloaded for a cell, check if that cell is still in the view or whether it has been re-used by another piece of data. If the cell has been re-used, then the image should be discarded. Otherwise, it should be switched back to the main thread to change the image on the cell. ([source](https://www.codementor.io/mattgoldspink/ios-interview-tips-questions-answers-objective-c-du1088nfb))
524 |
525 | ### What is a protocol? How do you define your own protocol?
526 |
527 | A protocol defines a list of required and optional methods for a class that adopts the protocol to implement. Any class is allowed to implement a protocol so that other classes can send message to it based on the protocol methods without knowing the type of class. An example of how a protocol is defined:
528 |
529 | A common instance protocols are used is providing a DataSource for UITableView or UICollectionView ([source](https://www.codementor.io/mattgoldspink/ios-interview-tips-questions-answers-objective-c-du1088nfb))
530 |
531 | ### What is JSON? What are the pros and cons?
532 |
533 | JSON stands for JavaScript Object Notation. According to [wiki](https://en.wikipedia.org/wiki/JSON), it is a file format that uses human-readable text to transmite data objects consisting of attribute-value pairs and array data types.
534 |
535 | Pros:
536 |
537 | - It is lighter than XML meaning that it can represent the same data in XML in fewer bytes. This makes network transmissions and read/writes faster
538 | - Since it is native to JavaScript, computationally-expensive XSL tranformations are not needed in order to extract data
539 |
540 | Cons:
541 |
542 | - Not as widespread as XML
543 | - Data is not readily streamable and has to be broken up into individual objects
544 | - Can't use comments
545 |
546 | ### What is the difference between not-running, inactive, active, background and suspended execution states?
547 |
548 | - **Not-running state** occurs when the app either has not be launched or was running but was terminated by the system.
549 | - **Inactive state** occurs where the app runs in the foreground but is currently not receiving events. (It may be executing other code though). This state is typically brief as apps transitions to other states.
550 | - **Active state** is where the app is running in the foreground and receiving events. This is the normal mode for foreground apps.
551 | - **Background state** occurs when the app is in the background and executing code. Apps typically enter this state on their way to being suspended. Apps that require extra execution time may remain in this screen longer. Apps being launched directly into the background enters this state instead of inactive state.
552 | - **Suspended state** is where the app is in the background but it is not executing code. Apps will remain in memory, but are removed by the system if low-memory condition occurs in order to make more space for foreground apps.
553 |
554 | ### Is it faster to iterate through an NSArray or an NSSet?
555 |
556 | It depends. NSSet is faster to iterate through if the order of the items in the collection is not important. The reason is because NSSet uses hash values in order to find items while NSArray has to iterate through its entire contents to find a particular object. ([source - #25](https://medium.com/cocoaacademymag/25-ios-interview-questions-and-answers-for-junior-developers-19bfe6e99b0))
557 |
558 | ### What is KVO?
559 |
560 | KVO stands for *Key-Value Observing*. It allows a controller or class to *observe* when a property value changes.
561 |
562 | ## Memory Management
563 |
564 | ### Why do you generally create a weak reference when using self in a block?
565 |
566 | Sometimes it is necessary it capture self in a block such as when defining a callback block. However, since blocks maintain strong references to any captured objects including self, this may lead to a strong reference cycle and memory leak.
567 |
568 | Instead, capturing a weak reference to self is recommended in order to avoid this issue
569 |
570 |
571 | ### What is memory management handled on iOS?
572 |
573 | iOS uses something called ARC which stands for Automatic Reference Counting. When an object is said to have a strong reference to it, ARC increase its retain count by 1. When the retain count of an object reaches 0, the object will typically be deallocated if there are no more strong references to it. Unlike garbage collection, ARC does not handle reference cycles automatically.
574 |
575 | > What is ARC?
576 |
577 | Automatic Reference Counting (ARC) provides automatic memory management for all Objective-C object. Developer no need to manually reain and release operations.
578 |
579 | ### What is the difference between *weak* and *strong*?
580 |
581 | First, objects are *strong* by default.
582 |
583 | - ***Strong*** means that the reference count will be increased and the reference to it will be maintained through the life of the object.
584 | - ***Weak***, means that we are pointing to an object but not increasing its reference count. It’s often used when creating a parent child relationship. The parent has a strong reference to the child but the child only has a weak reference to the parent. ([source](https://medium.com/ios-os-x-development/ios-interview-questions-13840247a57a))
585 |
586 | Common instances of ***weak*** references are delegate properties and subview/controls of a view controller's main view since those views are already strongly held by the main view. ([source](http://stackoverflow.com/questions/11013587/differences-between-strong-and-weak-in-objective-c))
587 |
588 | ### What is a memory leak?
589 |
590 | A memory leak commonly occurs when an object is allocated in such a way that when it is no longer in use or needed, it is not released. In iOS programming, you create certain objects with weak references in order to avoid a strong to strong relationship that creates a retain cycle and a memory leak.
591 |
592 | ### What is a retain cycle?
593 |
594 | Retain cycles can occur when memory management is based on retain count. This typically occurs when two objects strongly reference each other. As a result, the retain count of either object will never reach zero and deallocated from memory (hence retaining each other).
595 |
596 | ### What is the difference between *copy* and *retain*?
597 |
598 | Calling *retain* on an object will increase its *retain* count by one. When the *retain* count of an objective reaches 0, the object will be deallocated and released from memory.
599 |
600 | When you *retain* an object, you share the same version with whoever passed the object to you. But when you *copy* an object, you do not share the same version of the object that was passed to you. Instead, a duplicate of that object is created with duplicated values.
601 |
602 | ### What is the difference between a stack vs a heap?
603 |
604 | A stack is a region of memory where data is added or removed in a last-in-first-out (LIFO) order. According to [Ates Goral](http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap), it is the memory set aside as scratch space for a thread of execution. Meanwhile the heap is memory set aside for dynamic allocation. Unlike the stack, you can allocate a block at any time and free it at anytime.
605 |
606 | Note: In Objective-C, all objects are always allocated on the heap, or at least should be treated as if on the heap.
607 |
608 | ### What are “strong” and “weak” references? Why are they important and how can they be used to help control memory management and avoid memory leaks?
609 |
610 | When developer create the objects the default references is set as *strong*, and this will prevents the ARC(Automatic Reference Count) from removing the object from memory. If we don't deinitialized the object while we are not using, this will cause the memory leak. Upon time, the application might occur the error which is run out of the memory.
611 |
612 | So the *weak* reference is to slove this issue, when we create a weak reference we are pointing to an object without increasing reference count.
613 |
614 | Common instances of ***weak*** references are delegate properties and subview/controls of a view controller's main view since those views are already strongly held by the main view. ([source](http://stackoverflow.com/questions/11013587/differences-between-strong-and-weak-in-objective-c))
615 |
616 |
617 | ## Thread Management
618 |
619 | ### What is the difference between synchronous and asynchronous task?
620 |
621 | Synchronous tasks wait until the task has been completed while asynchronous tasks can run in the background and send a notification when the task is complete.
622 |
623 |
624 | ### What is GCD and how is it used?
625 |
626 | GCD stands for Grand Central Dispatch. According to [Ray Wenderlich](https://www.raywenderlich.com/60749/grand-central-dispatch-in-depth-part-1), it offers the following benefits
627 | - Improving your app's responsiveness by helping to defer computationally expensive tasks and run them in the background.
628 | - Providing an easier concurrency model than locks and threads and helps to avoid concurrency bugs.
629 | - Potentially optimize your code with higher performance primitives for common patterns such as singletons.
630 |
631 | In other words, GCD provides and manages queues of tasks in the iOS app. This is one of the most commonly used API to manage concurrent code and execute operations asynchronously. Network calls are often performed on a background thread while things like UI updates are executed on the main thread.
632 |
633 |
634 | ## Unit Testing / UI Testing
635 |
636 | ### What is the purpose of Unit/UI testing? What are the benefits?
637 |
638 | Unit/UI testing are the basic of test-driven development. This development approach allows you to codify requirements for your code before you implement it. Unit tests are important to make sure that code meets its design and requirements and behaves as expected. Parts of the program are segregated and tested to ensure that individual parts are working correctly.
639 |
640 | # Algorithm Resources
641 |
642 | #### [swift-algorithm-club](https://github.com/raywenderlich/swift-algorithm-club): Algorithm and data structures in Swift
643 |
644 |
645 |
646 |
647 |
648 |
649 |
650 |
651 |
652 |
--------------------------------------------------------------------------------