iOS Interview Questions and Answers
iOS Interview Questions and Answers
A question we are frequently asked, usually by less experienced iOS developers, is how to
prepare for an iOS interview. Most candidates look for our advice for preparing on technical
details such as what frameworks or libraries to invest their time in, what architectural
patterns should they be using, and other technical details. We believe that it is essential to
acquire the knowledge and develop a proper understanding of such tools and notions and
the ability to use them efficiently. Moreover, we like to introduce developers in thinking
somewhat differently when considering changing jobs or even starting a career in software
development, emphasising on the relationship and mutual benefits for both you, the
employee, and your future employer.If your goal as a candidate, is solely to receive an offer,
regardless the characteristics of the employer and team, then you should probably focus on
two aspects; answering all the questions correctly during the interview and convincing the
interviewers that you can deliver what they require. You can approach interviews as a
“number’s game” where the more of them you attend, the more offers will get if you’re
meeting the criteria, especially when the demand for iOS developers in the job market is
high. There are multi-billion active Apple devices in the world. With the number of iOS
users growing steadily across the world, the future looks bright for iOS app developers.
Apple and iOS devices continue to have a loyal customer base, helped in part by innovative
new devices such as Apple TV and Apple Watch.There has never been a better time to
become an iOS developer. However, if you have already given an iOS interview, or have
more questions, we encourage you to submit it with subject as iOS Interview Questions and
Answers to sandeep.challa73@gmail.com.I will answer them for you.This document
continues the work and I will update it every week. In this week edition, I added several
new things from my experience and companies where I worked to help you be ready for
iOS interview questions now. I updated the article to fully focus on Swift, since Objective-
C has become rarer, and added questions on Fundamentals of iOS, Unit Testing and
Architecture for Scale.When you’re preparing for your technical iOS interview, it’s
important to understand what you could be asked about topics and what is expected from a
seasoned iOS developer. These questions and topics (in one form or another) are used by
many companies to gauge the level of experience in an iOS candidate. They cover various
aspects of iOS development and aim to touch upon a broad understanding of the platform.
Senior developers are expected to be able to ship full iOS products from start to finish, after
all. But in large companies with big iOS development teams (think 25+ people)
specialisation and focus on a deep knowledge of a specific problem such as networking also
occurs though. This is by no means an exhaustive list, but it can help you prepare for your
upcoming technical iOS interview.
The questions covered in this post touch upon a broad spectrum of topics iOS developers
should know. This is by no means a comprehensive list. These questions are based on
research I’ve done. This approaches interview prep as a holistic overview of iOS topics and
concerns every iOS application has. It breaks down questions into the following groups: UI-
related questions (UIView, AutoLayout, etc.), storage questions (persistence, user defaults,
core data, etc.), networking (http, NSURLSession, Alamofire, etc.), and design patterns and
architecture questions (MVC, MVVM, SOLID, etc.). It has been a great help for more than
a thousand of developers who used it help them with interview prep.
I am sure that if you read all questions answer, then you will be crack your next interview.
All the best.
1. Intelegain Technologies
2. Infosys
3. Reliance General
4. India Infoline
5. Meru Cab
6. Thyrocare
7. Interview-1
8. Advanced Interview Questions
9. Interview - 2
10. Interview - 3
11. Call Ambulance
12. Shoppers Stop
13. Saint Gobain
14. Airtit
15. Synergy Technology Service
16. Cousins Infotech
17. Vasudhara Vision
18. Nanostuffs Technologies
19. HN Web Marketing
20. Exceptionaries Technologies
21. Surebot Technology Solution
22. Zomato
23. XIPHIAS Software TechnologiesXIPHIAS Software Technologies
24. Capillary Technologies
25. Volansys Technologies
26. NeoSOFT Technologies
27. Adaps
28. Space-O Technologies.
29. TimesOfMoney
30. Capegemini
31. 24/7 Software
32. GyanMatrix
33. Asterika Infotech
34. NeoQuant Solutions
35. Infrasoft Technologies
36. GOQII
37. OneKosmos
38. Reliance Mutual Fund
39. Network18
40. Emproto Technologies
41. Bruviti
42. Leap & Scale
43. Wipro
44. XEBIA IT
45. Drona HQ
46. Globant
47. Angel Broking
48. Welldoc
49. Synchronous Technology
50. Jet Synthesys
51. L&T Infotech
52. Moofwd
53. Futurism Technology
54. TCS
1. What is delegate?
2. What is need of protocol?
3. What is diff between delegate and notification?
4. Want is collection type in Objective-C and Swift?
5. What is extension in Swift?
6. What is different between Swift and Objective-c?
7. What is sub classing?
8. Oops concept
9. What is difference between class, enum and structure?
10. What is difference between strong and weak?
11. What is optional chaining and optional binding?
12. What is meaning of following in Swift
13.What is access specifier in iOS?
14.What are higher order methods?
1. What was the latest version of iOS you worked with? What do you like about it and
why?
2. What is an iOS application and where does your code fit into it?
3. What features of Swift do you like or dislike? Why?
4. How is memory management handled on iOS?
5. What do you know about singletons? Where would you use one and where would
you not?
6. Could you explain what the difference is between Delegate and KVO?
7. What design patterns are commonly used in iOS apps?
8. What design patterns besides common Cocoa patterns do you know of? -> MVC
9. Could you explain and show examples of SOLID principles?
10. What options do you have for implementing storage and persistence on iOS?
11. What options do you have for implementing networking and HTTP on iOS?
12. How and when would you need to serialize and map data on iOS?
13. What are the options for laying out UI on iOS?
14. How would you optimize the scrolling performance of dynamically sized table or
collection views?
15. How would you execute asynchronous tasks on iOS?
16. How do you manage dependencies?
17. How do you debug and profile things on iOS?
18. Do you have TDD experience? How do you unit and UI test on iOS?
19. Do you code review and/or pair program?
1. What is protocol?
2. What is need of protocol in ObjectiveC?
3. Diff between notification and delegate
4. What type of constraints for auto layout for any view?
5. How you will implement scrollview for any long form?
6. What are steps to implement for push notifications?
7. If there are two views up and bottom, up-view is 60% of superview and 40% of
superview respectively, then what to do with constraint?
8. How to implement expand type uitableviewcell?
9. If I have dynamic content in tableviewcell, then how it will be calculated?
2. What is category?
3. What is extension?
1. About Projects
2. Difference between tableview and collection view
2. Which is better scroll view or page view or collection view and why
3. Difference between bounds and frame
If I want have a label in a uiview, what will be the bounds and frame
4. What are generics in swift?
5. What are MVC pattern..in depth?
6. What is in out parameters
7. Access specifier in swift
8. Stackviews advantages. why and when to use stackviews?
9. What are size classes? Explain with example
10. How to handle optional in swift?
11. Have you worked with Auto layout?
12. How to submit an app to app store?
13. What is app thinning?
14. What is a singleton class?
15. What are closures?
16. What is extension and when and why to use them?
17. When to use a collection view and when to use a tableview?
18. What are observables in swift?
Practical Task :
Save locations and create geo-fencing there with a radius of 100 meters. While entering or
exiting from that radius we should get one local notification.
1. What is optional?
2. Why optional feature is introduced in Swift?
3. How do you check whether optional has value or not?
4. How many way we check optional has value?
5. Is exclamation mark for unwrapping is good practice?
7. What is different between Swift extension and Objective-c category? Where you have
used extension in your project?
8. What are size class? How many size class?
9. I want to transfer value from ViewControllerA to ViewControllerB and also pass value
from ViewControllerB to ViewControllerA. How can I achieve this? If using delegate
protocol, then write code.
10. Difference between local notification and delegates?
11. Can model and view directly communicate? Can view and controller communicate?
How view and controller can communicate? Give example of uitableview for same.
12. UITableViewDelegate and UITableViewsource methods.
13. Application States
14. Difference between Suspended and Termination state
15. How you will decrease app size if your app's size is increasing?
16. In navigation controller, A-B-C-D, I want to come from D TO A, How is it possible?
17. Difference between is ? and ??
18. Difference between struct and class
20. What is optional Chaining?
21. Difference between closure and method
22. Why you use closure in your project? Example of closure. Write code.
23. Difference between Swift and Objective-c protocol
24.
Struct view() {
var str = "Hi"
}
Output:?
Class view() {
var str = "Hi"
}
Output?
25. Have you used an access specifier? Why you have used public Access specifier?
26. What is KVO?
27. What you have used for web services requests?
28. Difference between NSUrl and NSUrlSession
29. What you have used for not blocking your app while the web-service response is
coming?
30. What are blocks?
31. Difference between Blocks and Methods
1. What is multiplier?
2. Difference between multiplier and ratio.
3. I have one button and I want my button size will be changed according to device size,
what you will prefer? Multiplier or Ratio? Why?
4. Difference between struct and class.
5. What is stack and heap?
6. Can you explain MVC through UITableView?
7. HeightForRowAtIndexPath is view or controller part in MVC?
8. Difference between notification center and delegates?
9. What is category?
10. Query for last inserted row in SQL database.
11. I have array of 10000 dictionary. And In dictionary, I have name and age key. I want
find indexes of name as 'Manan Shah' in dictionary. How we can find?
12. How to take common elements from two array?
13. Why containsObject : Id why Id type in containsObject?
14. What is p12 file?
15. What is pem file?
16. What is benefit of Singleton object over static object?
17. Is it possible to update Singleton object?
18. Is it possible to update Singleton value?
19. Which delegate method called when app icon is clicked?
20. If I click on app icon while app is background which delegate method is called?
21. Which delegate method called when I click on push notifications?
22. Add column query in sqlite
23. What is method swizzling?
24. Difference between innerjoin and outerjoin?
25. Difference between strong and weak property.
26.Difference between nill and null.
27. What is completion handler?
28. Why we need completion handler?
29. Difference between completion handler and notification center.
30. Difference between frames and bounds.
1. Have you used iprinter or any way to print from your app?
2. What are different types trigger point of local notification? I.e location based
3. Why soap request? Why everyone use rest API?
4. Do you know SMTP? Is it soap type or rest type?
5. What is category in Objective-C?
6. What are blocks in Objective-C?
7. For API call, which you are working on, normal, aftp or any third-party library?
8. Difference between block and completion handler
9. What blocks basically do? Why we use blocks?
10. In navigation view controller, form is open from right to left. I want to open from
bottom to top. How? What type of presentation is there for bottom to top?
11. How many ways we can present view controller?
12. After getting data from web response, how to store or parse data?
13. What is Object mapping that helping Jon parsing?
14. In iphone,I want label at top side and in iPad I want label in center, how will I manage
this?
15. What kind of encryption you have managed in your application?
16. Have you used a third party for encryption, internet reachability?
17. Is apple have reachability methods?
18. You have called web service. Meanwhile, how can you check for network availability?
19. How can you manage 2 storyboard navigation?
20. Why table view cell separator leave some space before?
21. How to customize UIButton such as label comes under image?
22. How to make round button of square button using static property?
23. How to take multiple type of cell in uitableview? If you manage cell using if else if
condition, what other options?
24. Why we use struct?
25. Difference between struct and class?
26. In Struct and class init must be written or not? Like initwitjTitleandAge.
Strct {
Var title : String
Var age : Int
}
Class {
Var title : String
Var age : Int
}
27. Difference between
1. OOPS Features
2. Explain Object Overloading, Overriding
3. What are app delegate methods?
4. Application state
5. Which app delegate method is used for applicationstarting?
6. iOS Application starting point.
7. What is .h and .m file in objective c?
8. Explain viewdidload and viewwillappear.
9. What is IBOutlet and IBAction?
10. What is atomic and Nonatomic?
11. What is multithreading?
12. What is synthesize?
13. What is an interface in objective c?
14. How to show webservice json data in UI? How to mark get/post method for web-service
for json parsing?
15. Difference between NSArray & NSDictionary.
16. Which framework is used for our UI or Views?
17. How to pass data from one view controller toanother view controller?
18. What is cocoa pods?
19. What are constraints?
20. What is Plist?
22. What is NSUserDefault?
23. What is a combined string and divide string?
24. What is MVC?
25. What is autolayout?
26. What is stack view?
27. What is size class?
28. What is a gesture recognizer?
29. How to popup alert view controller?
30. How to put yes, no button in the alert view controller?
1. How Uber taxi type apps manages the signal strength and shows if the user have low
network?
2. Write a program to extract only upper case letter from given string.
3. Difference between tableview and collectionview
4. How to implement delegate in swift?
5. What is optional chaining in swift?
6. Write a program to reverse a string in swift?
Volansys Technologies
Location : Ahmedabad, Gujarat
Date : Mar, 2019
6. How is 'Set' different from 'Array'? List out different methods of 'Set'.
7. Functional programming?
8. Mutability in struct.
9. Codable advantages and disadvantages.
10. Extension limitations.
11. Any Vs. AnyObject.
12. Create a protocol which can only conform to classes.
13. Disadvantages of Core Data.
14. If let Vs. Guard let.
15. Unit test cases.
16. Code coverage.
17. Swift Vs. Objective-C.
1. What Is NSPredicate?
2. Which Class Will Be Used For Sorting?
3. Difference Between SOAP n REST?
4. Process To Integrate Google Map?
5. How To Add Custom Marker On Map?
6. What Is GCD?
7. How To Add Priority In Multithreading?
8. What Is Map() Function?
9. What Is Optional Binding And Optional Chaining?
10. Application States
11. Steps To Integrate FCM?
12. Delegate methods Of Firebase Notification ?
13. What Is Silent Notifications?
14. Difference Between NSArray And NSSet?
15. What Is Atomic and Non Atomic?
16. ViewController Life Cycle.
17. Difference Between Protocols And Notificationcenter.
18. How To Play Audio Video In App?
19. What is data task for URLSession?
20. Delegate and Data Source Methods Of Tableview.
21. What is safe area?
22. How To Share Something On Social Media (Like Fb, Twitter, Insta) From Ur App ?
23. Difference Between App Bundle And File Directory?
24. Types Of Provisioning Profile.
25. How To Record Audio And Video?
26. How To Solve Conflict In Git Repositories?
27. How To Handle Crashes In Swift ?
28. How To Do Unit Test In Xcode ?
29. How To Declare Custom Cell?
30. What Is The Use Of dequeuereusablecellwithidentifier ?
1. Difference between REST and SOAP api. Which one is most secure? Which one you will
choose for your application and Why?
2. What is new in Swift 5.1?
3. What is string interpolation in Swift 5.1?
4. Which tools is used for Crashlytics?
5. what is .dysm file? Where you can get that file?
6. ViewController Lifecycle
7. Difference between Class and Struct.
8. What is flag in memory for local variables?
9. In Swift, which inheritance support, multiple inheritance or multilevel inheritance?
10. Make one protocol and how to implement, write code.
11. Can protocol be file private?
12. Can we make init method in protocol?
13. What is QOS?
14. What is access specifier?
15. Difference between Open and Public.
16. How to pass data from one view controller to another view controller?
17. Types of apple account. What is for enterprise account?
18. What types of certificates are needed in iOS development and deployment?
19. Is distribution certificate support wild mark (*) ?
20. What is vary trait in auto layout?
21. What is content hugging priority?
Location : Mumbai
Date : March, 2021
1. What is singleton?
2. What is major changes in Swift 5, that is not in Swift 4.2 ?
3. Difference between FCM and APNS.
4. What is silent notification?
5. Is it possible to get silent notification via APNS ?
6. How to implement APNS?
7. How to get notification with image?
8. What is higer order function?
9. Difference between Class and Structure.
10. What is protocol?
11. Can we use multiple inheritance in Swift?
12. Tell me about Core Data Stack.
13. How to implement multi threading in Core Data?
14. How to implement multi threading in Swift?
15. What is content hugging priority?
16. What is content compression priority?
17. In iphone, I want to show tableview and In iPad, I want to show collection view.
How to do this?
18. What is CI/CD ?
19. How to know where memory leak happening?
20. Tell me procedure to upload app to appstore.
12. We are not getting response from api after much time and loader is still shown, how
can you handle this?
13. Why SOAP is more secure than REST?
14. Response is in which format in SOAP and in REST?
15. Do you know different background modes? i.e push notification, location, bluetooth,
audio play
16. Do you know optional in swift?
17. How push notification works?
18. What is use of reduced in higher order function?
19. What is new in xCode 10.2?
20. If you wanna go to another branch for doing some work, and after some time you
wanna come back to your previously saved work, how you can manage in GIT?
21. Design iphone landscape, how you go with it?
22. What is frame and bounds?
23. How you can add column in entity in core data that can be also added in next
release?
24. What is ssl pinning?
25. What you are using for giving security of data in your app?
4. VCA and VCB. There is one strong reference from VCA to VCB, then what happen
if VCB will be dismissed?
5. Can I have corner radius with shadow to view in swift?
18. What is content hugging priority and content resistance priority? Difference
between them.
19. What is encodable?
20. What is Core Data Stacks?
21. What is delete rule in Core Data?
22. How can you achieve memory management in Swift?
23. Have you ever used strong and weak reference in your project and Why?
24. Which design pattern have you used?
1. OOPS Concept.
2. Difference between encapsulation and abstraction.
3. How we achieve encapsulation and abstraction in iOS?
4. Write code for creating custom protocol?
5. How class confirm protocol in objective c and swift?
6. Application life cycle
7. Difference between background state and suspended state.
8. How much time code can be executed in background? What will occur after that?
What If I download something that can takes much time, what will be occur?
9. Which inheritance objective c support?
10. What is base class?
11. View Controller life cycle.
12. How many times Viewdidload and layoutsubviews called?
13. Which method will first called if I came from back button?
14. What will occur if I have tableview in uiscrollview, if I scroll?
15. What is UIResponder Chain?
16. What are UITextField delegate methods?
17. Which method called when I click on next, done button?
18. How cellForRowAtIndexPath methods works?
19. What is dequecellreusablecellidentifier? What are overloading of deque methods?
What are purpose for both?
20. What is GCD?
21. How we can achieve concurrency type in Objective C and Swift?
22. What is auto-release-pool?
23. What is ARC?
24. How APNS works?
25. What is RICH Notification?
26. Which design patterns are there?
27. What is MVC?
28. What is Singleton pattern?
1. Which location you used for current location, network location or gps location?
2. What is accuracy of GPS location?
3. How you will calculate for geo fencing in your mobile app?
4. Have you done battery optimization for gps or api calling?
5. What is polymorphism?
6. What is exception?
7. What is error?
8. Difference between error and exception?
9. Why it is require to handle exception?
10. Difference between asynchronous and synchronous calls.
11. How you have used async task?
12. Which are methods of async task? 4 Methods.
13. What is multithreading?
14. Which are methods of threads in Swift?
15. Difference between thread methods start and run>
16. What is difference between REST and SOAP api? Why SOAP is more sequre?
17. What methods of REST? GET, POST.
18. What are other methods rather than GET and POST?
19. Difference between GET and POST?
20. Difference between Core Data and Sqlite?
21. Why you use swift rather than Objective C?
22. What they signify? ?, ??, !!
23. Application Life cycle.
24. Difference between Inactive and Suspended.
25. Difference between Background and Inactive.
26. What is Singleton? Write code.
27. Write a program for sorting array. Quick sort, merge sort, Heap Sort
28. Write a program for get only numeric from "a,b,1,2,c,4,d,3"
29. Swap between two numbers without third variable?
6. 5 Ltrs jar & 3 Ltrs jar, I want to add 4 Ltrs in another jar, How can I?
7. What is code signing?
8. What information provisioning profile has?
9. What app Id include?
10. What is app group capability?
11. What is universal linking? If I click on link of flippant, it open specific product,
what it is?
Screening :
2nd Round :
1. What are new features in swift 5?
2. What is ABI Stability?
3. What is app thinning and why it has more power in new swift 5?
4. What are source, version, binary type compatibility?
5. Is there possibility for interoperability between objective c and swift? What are
things which are not interoperable between swift and objective c?
6. What is bridging header?
7. Is it possible to code written in swift is interoperable in objective c?
8. Have you worked with dependancy manger, Carthage, cocoa pods?
9. When we use pod deinit?
10. What will happened if I delete pod.lock file?
11. How to upload framework to cocoa pods?
12. Which cocoa pods version you are using?
13. Which access modifier you will use if you want to expose methods to different
module? -Open, Public
14. Difference between public or open?
15. What is internal access specifier?
16. How to use decoder and encoder ? How to map your model class struct with json
data?
17. Is it mandatory keep name of your struct para name same as json data?
18. Can we declare optional methods in swift protocol? That protocol can be used for
classes and structure both?
19. Is objective-C support struct?
20. What is SSL pinning?
21. Can we store object in user default?
22. What are best way to implement if large data is coming from core data and show
data on tableview?
23. Difference between collection view and tableview?
24. What are different delegate and datasource for UICollectionView?
25. Is ARC for swift or iOS?
26. Is outlet should be weak or strong?
27. What is capturelist in closure? Why to need mention [weak self] in closure?
1. What you do for battery management in your app while using GPS?
2. Which method of URLSessoin you can use to get data from REST api?
3. How can I be notified if all my api running in parallel will be completed its
excecution?
4. How we make sure all my api running parallel?
5. What are advantages of NSOperation over GCD?
6. Difference between class and struct
7. How to retain cycle occurs?
8. How do I find retain cycle? How to use instrument to check retain cycle?
9. What is unwind segue?
Location: Bangalore
Date: March, 2021
1-What is an iOS application and where does your code fit into it?
2-Whats fast enumeration and struct?
3-Explain View Controller Lifecycle events order ?
4-What are mutable and immutable types in Objective C?
5-Dispatch Barriers and Dispatch group in Swift 3
6-What is FRP (Functional Reactive Programming) and what are the options for
laying out UI frame and bounds on iOS?
7-Is a delegate retained and What is dynamic?
8-Outline the class hierarchy for a UIButton until NSObject.
9- Do you code review and/or pair program?
10-WHAT’S NEW IN XCODE 12
11-How to change the Application Name?
12-Whats the NSCoder class used for?
13-What is SpriteKit and what is SceneKit?
14-What is git stash and what is the function of ‘git stash apply’?
15-What is git reflog and Web hooks?
16-What will be output for below code.
17-What are the App states. Explain them?
18-Multitasking support is available from which version?
19 .What is Automatic Reference Counting (ARC) and How is memory
management handled in iOS?
20-iOS life cycle.
21.What is the Responder Chain?
22-What is the difference between delegates, notifications, KVC, KVO and
Notification Center?
23-What is posing in iOS?
24-What is atomic and nonatomic? Which one is safer? Which one is default?
25-What are the tools required to develop iOS applications and where can you test
Apple iPhone apps if you don’t have the device?
26-How do you manage dependencies?
27- Name the framework that is used to construct application’s user interface for iOS.
28-Name a few Git commands and explain their usage?
29- Which API is used to write test scripts that help in exercising the
application’s user interface elements and Do you have TDD experience? How
do you unit and UI test on iOS?
30-How would you securely store private user data offline on a device? What other
security best practices should be taken?
31-Codable Protocol
32-Why is JIRA used?
33-Consider the following code:
34-What is the use of SwiftLint in iOS?
35- What is Zendesk?
36-What is Jenkins?
37-Consider the following code:
38- What is the difference between Continuous Integration, Continuous Delivery,
and Continuous Deployment?
80-Collection
81-What is Deep Linking, HealthKit, Neural networks with Core ML?
82-.Can you spot the bug in the following code and suggest how to fix it:
83-What will be the output for below code.
84-What is the use of ? , ??, ! , Downcasting, zip?
85-What is Helper Objects and Cluster Class?
86-What is generics and the difference ANY and ANY OBJECT ?
87-Differentiate Foundation vs Core Foundation
88- Readers-Writers
89-Retain cycle or Retain loop.
90-What’s your preference when writing UI’s, Xib files, Storyboards or programmatic
UIView?
91-strong, weak, unsafe_unretained, autoreleasing, NSAutoReleasePool, release and
drain?
92-What is AutoLayout? What does it mean when a constraint is "broken" by iOS?
93-A product manager in your company reports that the application is crashing. What
do you do?
94-What makes React Native special for iOS?
95-Consider the following code:
96-How should one handle errors in Swift?
97.Should I learn Swift or Objective-C and Differences Between Swift And
Objective-C?
98.Subclass, Category and Extensions in Objective C
99. What is an API
100.What is the biggest difference between NSURLConnection and NSURLSession?
101.Explain and show examples of SOLID principles?
102.What is data encapsulation, Polymorphism and Abstract?
103.Swift’s Equitable and Comparable Protocols
104. Mention what is the characteristics of Switch Enums in Swift?
105.What is method swizzling in Objective C and why would you use it?
106.how to check crash reports client in iOS app?
107.Property Observers
108.Higher order functions in Swift?
109.Apple Push Notification Services?
110.What is Concurrency and Objectives of Concurrency?
111.Operations, Operation Queue and Grand Central Dispatch synchronous versus
asynchronous connections.
112.What considerations do you need when writing a UITableViewController which
shows images downloaded from a remote server?
113. Difference between struct and class swift
114. What are some ways to support newer API methods or classes while maintaining
backward compatibility?
115. In Swift, what are fail-able, throwing initialisers and Tuples?
116. What is an “app ID”, “bundle ID” , App Bundle and Signing?
117. if let, if var, guard let, guard var and defer statements in swift
118.Please explain Access Levels in Swift?
119. networking, Get, Post, REST, HTTP, HTTPs, JSON What’s that?
120.List out what are the control transfer statements used in Swift?
121.What is Property?
122. What are the most important application delegate methods a developer should
handle ?
123. How do you debug and profile code on iOS?
124. What is three triggers for a local notification and use of UserNotifications?
125. nil / Nil / NULL / NSNull
126. What is the difference between functions and methods in Swift?
127.What are optional binding and optional chaining in Swift?
128. What's the syntax for external parameters?
129.Would you consider yourself a Swift expert?
130.What are blocks and how are they used?
131.What is the difference Non-Escaping and Escaping Closures ?
132.What is the difference SVN and Git ?
133.What is the difference between LLVM and Clang?
134.How many different ways to pass data in Swift ?
135. What kind of benefits does Xcode server and Xcode Bot have for developers ?
136.What are layer objects and Explain unwind segue?
137.How to convert Swift String into an Array?
138.why swift is protocol oriented language
139.What iOS architectures do you know that scale and design patterns are commonly
used in iOS apps, which one better for iOS Development?
140.New Build System in Xcode?
141.What’s new in Swift 5.0
142.Mobile Device Management (MDM) in iOS?
143.Which is testing framework is best?
144.How much test coverage is enough?
145.Should I unit test views and/or view controllers?
146.Doesn’t adding unit tests take more time?
147.setUp() And tearDown() in XCTest?
148.Designated Initialisers and Convenience Initialisers?
149.Local, Global and Static variables?
150.Which Inheritance will supports in Swift Single, Multiple or Multilevel?
151.Debugging skills in iOS
152.What difference between 'self' and ‘Self’?
153.What’s the difference between == and ===?
154.Write a Palindrome program
155.What is QualityOfService in operation?
156.Write a String reverse program
157.When would you use Swift’s Result type?
158.What is a UUID, and when might you use it?
159.What is the difference between the Float, Double, and CGFloat data types?
160.Types of ranges?
161.How would you explain Dynamic Type to a new iOS developer?
162.What is apple developer/enterprise account??
163.Difference between network location and gps location?
164.I have written for loop from 1 to 10. But when i=7 then then it comes out from
loop. I have not written any specific keyword nor exception generated. How it is
possible?
165.Difference between FCM and APNS?
166.Determine index of one integer in another integer - online programming question?
167.Write a program to find missing number of array of 1 to n?
168.Write a program to distinguish lowercase and uppercase character from String in
swift?
169.Can we make a class-specific protocol?
170.Can we declare an optional protocol method in swift?
171.Can we define property in extension?
172.Can we define property in protocol?
173.How we stop notification to be sent to device who is uninstalled?
174.What is p12 and pem file?
175.What are join in sql? Explain Types of Join?
176.Add column in SQLite?
177.If there are two views up and bottom, up-view is 60% of superview and 40% of
superview respectively, then what to do with constraint?
178.What is Content Hugging and Content Compression Resistance Priority?
179.What method is called after tap back button in ios?
180.What is StackView? What is advantage and distribution type of stackview?
181.Enlist different background modes?
182.How does CloudKit differ from Core Data?
183.What are the different ways of showing web content to users?
184.How much experience do you have using iBeacons? Can you give examples?
185.What are the advantages and disadvantages of SwiftUI compared to UIKit?
186.Can you talk me through some interesting code you wrote recently?
187.Do you have any favorite Swift newsletters or websites you read often?
188.How do you stay up to date with changes in Swift?
189.If you could have Apple add or improve one API, what would it be?
190.What books would you recommend to someone who wants to learn Swift?
191.What open source projects have you contributed to?
192.Have you ever filed bugs with Apple? Can you walk me through some?
193.What experience do you have working on macOS, tvOS, and watchOS?
194.What is the purpose of code signing in Xcode?
195.What steps do you take to identify and resolve battery life issues?
196.What steps do you take to identify and resolve a memory leak?
197.What steps do you take to identify and resolve performance issues?
198.How much experience do you have using Face ID or Touch ID? Can you give
examples?
199.How would you explain App Transport Security to a new iOS developer?
200.How would you calculate the secure hash value for some data?
201.In which situations do Swift functions not need a return keyword?
202.Apart from the built-in ones, can you give an example of property wrappers?
203.Can you give useful examples of enum associated values?
204.What are opaque return types?
205.How would you explain SwiftUI’s environment to a new developer?
240.What will be output for below code snippet? Also, analyze the memory
performance for this code?
241.What is the difference between the consumable and non-consumable type of in-
app purchase?
242.Swift is a static language and Objective-C dynamic language. What does it mean?
243.What is the output of the following Program? let numbers = [1, 2, 3, 4]?
244.Structures can be inherited(True/False)?
245.What is the Output of Following Program var randomly Array: [AnyObject] =
[1,1.2,”Hello”] print (randomArray)?
246.What is the Output Of Following Program?
247.Is it possible to create multiple storyboards in single project. If yes how to switch
from one storyboard to another?
248.what are binaries required to install the app to device?
249.How much will you rate yourself in iOS?
250.How much experience do you have in iOS?
251.Have you done any iOS Certification or Training?
252.what OAuth?
253.Why Choose Struct Over Class?
254.Combine Framework in iOS?
255. Publishers in Combine Framework?
256. Operators in Combine Framework?
257. Subscribers in Combine Framework?
258.Static vs Dynamic Dispatch in Swift?
259.Static and Class Keyword in Swift?
260.How to split this array [0, 1, 2, 0, 1, 2] to subarray off 0,1,2?
261.I didn't hear back immediately after my interview. Am I rejected?
262.Can I re-apply to a company after getting rejected?
263.Why do you want to work for Microsoft?
264.How you will store user info (username, password or token) securely in iOS?
1-What is an iOS application and where does your code fit into it?
This is a big-picture question asked, in one form or another, to gauge your understanding of
what an iOS application is, and where the code you write fits in it and in the iOS system
overall.
We might think the apps we build are something special because they cover a unique use
case. But your typical iOS application is just a giant, glorified run loop. It waits for user
input and gets interrupted by external signals such as phone calls, push notifications, home
gestures/button presses, and other app life cycle events. The only difference is that instead
of being just a simple main loop function that gets launched every time the user taps on
your app icon, it has a higher level of abstraction, UIApplication, AppDelegate, and
SceneDelegate that developers work with.
The rest of the code you write to implement the business logic of your app is placed
somewhere in the “trigger points” delegated by that main loop to our app via AppDelegate
or SceneDelegate. Before iOS 13 AppDelegate was responsible for receiving all external
events for your application and spinning up the UI; but starting with iOS 13 all UI-related
logic was moved to SceneDelegate.
That’s it. Simple. The code you write for your app can be as simple as a method/function
call, or as complex as VIPER architecture. It’s your choice.
Typically developers think of iOS apps as the MVC code they write and the complex
intricate details of the implementation, which is true. But if you take a step back and look at
the big picture, you can see what iOS apps really are - a run loop.
Apple gave a very good explanation on this by saying that it is called to notify the view
controller that its view has just laid out its subviews.
In another word, viewDidLayoutSubviews is called every time the view is updated, rotated
or changed or it’s bounds change.
But know that with viewDidLayoutSubviews, it only take places after all the auto layout or
auto resizing calculations on the views have been applied. Meaning the method
viewDidLayoutSubviews is called every time the view size changes and the view layout has
been recalculated.
- viewDidAppear
Notifies the view controller that its view was added to a view hierarchy.
- viewWillDisappear
Before the transition to the next view controller happens and the origin view controller gets
removed from screen, this method gets called.
- viewDidDisappear
After a view controller gets removed from the screen, this method gets called. You usually
override this method to stop tasks that are should not run while a view controller is not
on screen.
A dispatch group lets us easily keep track of multiple blocks that have been dispatched to
queues and be notified when they are complete. They make things much simpler by
allowing us to not need to keep state of all the blocks that we have dispatched. Now it's not
desperately complicated to do so, we could just keep a count of how many blocks we have
dispatched, or an array of the dispatched blocks and decrement (or remove from the array)
on completion. Since this is such a common thing to do Apple have done this for is, it's
worth noting that this can be less simple to implement if we dispatch the same block
multiple times, or are dispatching blocks across several different queues.
6-What is FRP (Functional Reactive Programming) and what are the options for
laying out UI frame and bounds on iOS?
Functional reactive programming (FRP) is the new hotness in iOS/Swift, JavaScript, and
other dev communities. Except that it’s actually not that new. Expect this question either on
Swift features, or as a bigger architectural and conceptual discussion question.
Functional Reactive Programming (FRP) is a declarative programming paradigm that
combines functional programming and reactive (async data flow programming) paradigms.
It is a declarative style of programming where you declare what your code does rather than
state how it does it. The reactive component of FRP allows us to introduce and describe the
concept of time, which is hard to work with in pure functional programming. FRP helps us
deal with user input and the asynchronous nature of iOS applications in general; user input
happens at some point in time, networking will finish some time in the future, etc.
FP and FRP rely on higher-order functions such as map, reduce, and filter that take
functions as arguments and return other functions, which makes them highly composable.
Swift doesn’t have native support for FRP, but there are two excellent libraries that
implement functional reactive programming concepts and make them easily available to us:
ReactiveCocoa and RxSwift.
In iOS 13, Apple also announced a new FRP framework built into iOS called Combine.
Combine is effectively an FRP framework implementation similar to RxSwift. The two
advantages it has: it’s integrated with SwiftUI allowing it to bind UI elements to data
changes, and it’s built-in and supported by Apple. Disadvantages are: it’s less mature than
RxSwift and Apple will be slow to make changes and additions to it.
FRP is becoming more commonplace in iOS apps and will be used more with Apple's
official support of this programming paradigm with Combine. iOS developers should start
embracing it.
Knowing your options for laying out things on the screen is crucial when you need to solve
different UI challenges on iOS. This question helps gauge your knowledge about how you
put place and align views on the screen. When answering this question, you should at least
mention CGRect, Frames and, AutoLayout, and SwiftUI, but it would be great to mention
other options such as Texture (ASDK), ComponentKit and other Flex box and React
implementations on iOS.
Go-to options for laying out views on the screen are good old CGRect Frames and
AutoLayout. Frames, along with auto-resizing masks, were used in the past before iOS 6
and are not a preferred option today. Frames are too error-prone and difficult to use because
it’s hard to calculate precise coordinates and view sizes for various devices.
Since iOS 6 we have AutoLayout, which is the go-to solution these days and which Apple
prefers. AutoLayout is a technology that helps you define relationships between views,
called constraints, in a declarative way, letting the framework calculate precise frames and
positions of UI elements instead.With iOS 13, Apple introduced a new approach for laying
out views - SwiftUI, which is a declarative approach that supports FRP (functional-reactive
programming) data bindings with Combine. FRP and declarative UI are not new concepts,
but SwiftUI and Combine are new frameworks from Apple that support it. The declarative
nature of SwiftUI allows you to declare your UI elements very concisely and then later
through data bindings declare what parts of the UI, such as text labels for example, to
update upon what data model changes. In effect, it allows you to do what was already
possible with RxSwift before, but now with Apple frameworks.
There are other options for laying out views, such as ASDK (Texture), ComponentKit, and
LayoutKit, and some of them are more or less inspired by React and others solve layout A
synchronicity differently. These alternatives are good in certain scenarios when, for
example, you need to build highly dynamic and fast table views and collection views.
AutoLayout is not always perfect for that and knowing there are other options is always
good.
NOTE: we’ll see how SwiftUI proves itself solving complex UI problems and complex
async UI layout problems in the future, it’s a very new technology as of the time of this
writing.
Not mentioning at least AutoLayout and the fact that frames are hard to get right will be a
red flag for your interviewer. These days no sane person would do CGRect frame
calculations unless it's necessary (for example, when you do crazy drawings).
It won’t be a red flag yet, but mention SwiftUI and that this likely will be what Apple will
push on us in coming years.
The frame of a view is the rectangle, expressed as a location (x,y) and size (width,height)
relative to the superview it is contained within. The bounds of a view is the rectangle,
expressed as a location (x,y) and size (width,height) relative to its own coordinate system
(0,0).
An all-new design groups all critical information about each of your apps together in one
place. Choose any app from any of your teams, then quickly navigate to inspect crash logs,
energy reports, and performance metrics, such as battery consumption and launch time of
your apps when used by customers.
Devices:
• The Add Device sheet in the Devices and Simulators window is now resizable.
• The Devices and Simulators window permits selecting multiple devices in the
navigator, so they can be unpaired together. This eases the removal of old records for
devices that are no longer in use.
Simulator:
• Simulator can display a simulated device in full-screen mode, or tile its window
alongside Xcode. Now enjoy split-screen mode with Xcode and Simulator side by
side.
Universal Apps:
• Xcode 12 is built as a Universal app that runs 100% natively on Intel-based CPUs
and Apple Silicon for great performance and a snappy interface.
• It also includes a unified macOS SDK that includes all the frameworks, compilers,
debuggers, and other tools you need to build apps that run natively on Apple Silicon
and the Intel x86_64 CPU.
• When you open your existing project in Xcode 12, your app will automatically get
updated to generate release builds & archives as Universal apps.
Store Kit (Local Test Environment);
• Xcode 12 supports testing in-app purchases (IAP) directly in Simulator or on a
connected device, using a new local StoreKit test environment.
• It means you can configure IAP information locally for testing, before setting it up in
App Store Connect and without a connection to App Store servers.
Debugging:
• When a process pauses at a breakpoint, Xcode displays the hit count for that
particular breakpoint location as part of the breakpoint’s annotation in the editor.
Example: “Breakpoint 1.1 (10)”, where 10 means that location 1.1 has been hit 10
times.
Swift Packages:
• You can now declare conditions for a Swift package’s target dependencies, such as
limiting the dependencies by the platform.
• Swift packages can now contain resources such as images, asset catalogs,
storyboards, and other files.
Playgrounds:
• Xcode Playgrounds can now import and use Swift packages and frameworks. Select
the Build Active Scheme checkbox in the playground’s File inspector and ensure that
the active scheme builds the package or framework target.
Project Editor:
• The Document Types, Exported Type Identifiers, and Imported Type Identifiers
panes support the new templated document icons in macOS 11.
Interface Builder:
• Find and Replace now includes matches in attributed string literals.
• Interface Builder now has a Current Date option for NSDatePicker.
Press command-I to bring up the Info window, then navigate to the Build tag. Set the
Configuration drop-down to read All Configurations, then look for a setting called
Product Name under the Packaging heading. Change that value to the name you
want for your compiled applications and, in the immortal words of Bugs Bunny:
Viola! Do a clean then build and your application will take on the new name.
14-What is git stash and what is the function of ‘git stash apply’?
Often, when you’ve been working on part of your project, things are in a messy state and
you want to switch branches for some time to work on something else. The problem is, you
don’t want to do a commit of half-done work just so you can get back to this point later.
The answer to this issue is Git stash.
Stashing takes your working directory that is, your modified tracked files and staged
changes and saves it on a stack of unfinished changes that you can reapply at any time.
If you want to continue working where you had left your work then ‘git stash
apply‘ command is used to bring back the saved changes onto your current working
directory.
print(“Apple”)
DispatchQueue.main.async{
print(“iPod”)
DispatchQueue.main.async{
print(“iPhone”)
}
DispatchQueue.global().sync{
print(“iPad”)
}
DispatchQueue.main.sync{
print(“Mac”)
}
print(“Apple Watch”)
}
print(“Apple TV”)
First, it will print “Apple”.
Next logic is contained in a 'main' async event. So it's postponed. The next thing it will print
is "Apple TV". Once the main thread is free, our first main.async task will run. So “iPod”
will print.
Next to its main.async task again. For this to execute, the main thread needs free. Since
we're still in the middle of the control flow, It will move to DispatchQueue.global().sync.
Read carefully, that it's dispatching sync not async. That means that the main thread is
frozen until the code dispatched to the global queue is done.Then it will print “Apple
Watch”. DispatchQueue.main.sync will crash app.
• Background state: The app is in the background and executing code. Most apps
enter this state briefly on their way to being suspended. However, an app that
requests extra execution time may remain in this state for a period of time. In
addition, an app being launched directly into the background enters this state
instead of the inactive state. For information about how to execute code while in
the background, see “Background Execution and Multitasking.”
• Suspended state: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. When a low-memory condition occurs, the system may purge suspended apps
without notice to make more space for the foreground app.
iOS 4 and above supports multi-tasking and allows apps to remain in the
background until they are launched again or until they are terminated, left side
diagram for iOS 4 and above and right side diagram for iOS 3 and below.
However, if you don’t want the variable to be weak AND you are sure that it can’t be
accessed after the corresponding instance has been deallocated, you can use unowned.
By declaring it [weak self] you get to handle the case that it might be nil inside the closure
at some point and therefore the variable must be an optional. A case for using [weak self] in
an asynchronous network request, is in a view controller where that request is used to
populate the view.
Memory management is very important in any application, especially in iOS apps that have
memory and other hardware and system constraints. This question refers to ARC, MRC,
reference types, and value types.
Swift uses Automatic Reference Counting (ARC). This is conceptually the same thing in
Swift as it is in Objective-C. ARC keeps track of strong references to instances of classes
and increases or decreases their reference count accordingly when you assign or unassigns
instances of classes (reference types) to constants, properties, and variables. It deallocates
memory used by objects whose reference count dropped to zero. ARC does not increase or
decrease the reference count of value types because, when assigned, these are copied. By
default, if you don’t specify otherwise, all the references will be strong references.
This is a must know for every iOS developer! Memory leaks and app crashes are all too
common due to poorly managed memory in iOS apps.
CORE OS and CORE SERVICES LAYERS - These interfaces are mostly C-based and
include technologies such as Core Foundation, CFNetwork, SQLite, and access to POSIX
threads and UNIX sockets among others.
MEDIA LAYER –The Media layer contains the fundamental technologies used to support
2D and 3D drawing, audio, and video. This layer includes the C-based technologies
OpenGL ES, Quartz, and Core Audio. It also contains Core Animation, which is an
advanced Objective-C based animation engine.
COCOA TOUCH
In the Cocoa Touch layer, most of the
technologies use Objective-C. The frameworks at these
layers provide the fundamental infrastructure used by
your application. For example, the Foundation
framework provides object-oriented support for
collections, file management, network operations, and
more. The UIKit framework provides the visual
infrastructure for your application, including classes for
windows, views, controls, and the controllers that manage those objects. Other frameworks
at this level give you access to the user’s contact and photo information and to the
accelerometers and other hardware features of the device.
When an event happens in a view, for example a touch event, the view will fire the event to
a chain of UIResponder objects associated with the UIView. The first UIResponder is the
UIView itself, if it does not handle the event then it continues up the chain to until
UIResponder handles the event. The chain will include UIViewControllers, parent UIViews
and their associated UIViewControllers, if none of those handle the event then the
UIWindow is asked if it can handle it and finally if that doesn't handle the event then the
UIApplicationDelegate is asked.
methods are typically grouped into a protocol. A protocol is basically just a list of methods.
The delegate
protocol specifies all the messages an object might send to its delegate. If a class conforms
to (or adopts) a protocol, it guarantees that it implements the required methods of a
protocol. (Protocols may also include optional methods).In this application, the application
object tells its delegate that the main startup routines have finished by sending it the
applicationDidFinishLaunching: message. The delegate is then able to perform additional
tasks if it wants.
Notification centre: it determines the observers of a particular notification and sends the
notification to them via a message. The methods invoked by the notification message must
conform to a certain single-parameter signature. The parameter of the method is the
notification object, which contains the notification name, the observed object, and a
dictionary containing any supplemental information.Posting a notification is a synchronous
procedure. The posting object doesn’t regain control until the notification centre has
broadcast the notification to all observers. For asynchronous behaviour, you can put the
notification in a notification queue; control returns immediately to the posting object and
the notification centre broadcasts the notification when it reaches the top of the
queue.Regular notifications that is, those broadcast by the notification centre—are
intraprocess only. If you want to broadcast notifications to other processes, you can use the
distributed notification centre and its related API.Notification Center is an observer pattern,
The NSNotificationCenter singleton allows us to broadcast information using an object
called NSNotification.
The biggest difference between KVO and Notification Center is that KVO tracks specific
changes to an object, while Notification Center is used to track generic events.
24-What is atomic and nonatomic? Which one is safer? Which one is default?
Atomic and non-atomic refers to whether the setters/getters for a property will atomically
read and write values to the property. When the atomic keyword is used on a property, any
access to it will be “synchronised”. Therefore a call to the getter will be guaranteed to
return a valid value, however this does come with a small performance penalty. Hence in
some situations nonatomic is used to provide faster access to a property, but there is a
chance of a race condition causing the property to be nil under rare circumstances (when a
value is being set from another thread and the old value was released from memory but the
new value hasn’t yet been fully assigned to the location in memory for the property).You
can use this attribute to specify that accessor methods are not atomic. (There is no keyword
to denote atomic.)nonatomic.Specifies that accessors are nonatomic. By default, accessors
are atomic. Properties are atomic by default so that synthesised accessors provide robust
access to properties in a multithreaded environment—that is, the value returned from the
getter or set via the setter is always fully retrieved or set regardless of what other threads
are executing concurrently. If you specify strong, copy, or retain and do not specify
nonatomic, then in a reference-counted environment, a synthesised get accessor for an
object
If you specify nonatomic, a synthesised accessor for an object property simply returns the
value directly.
25-What are the tools required to develop iOS applications and where can you test
Apple iPhone apps if you don’t have the device?
• Mac/MacMini: It is necessary for us to get a Mac with the Intel-based processor
running on Mac OS. Not to worry, if we have our own PC, we can still develop iOS
apps through Mac Mini.
• Xcode: Xcode is the Apple IDE (Integrated Development Environment) that is used
for both iOS apps and MAC OS. It provides us a visual layout editor and a code
editor that can deal with the logic, user interface and response behind the scene.
• Swift Programming Language: In the code editor, the logic will be written in a
programming language that is invented by Apple, called Swift.
• Apple Developer Program: This program allows the developer to push our app live
on the App store so that the customers and downloaders all over the world can
download our app and use it.
Every iOS developer should understand why copy-pasting third-party libraries into your
codebase leads to a maintenance nightmare when several libraries could depend on two
different versions of another library, causing mismatches and compile and runtime issues.
Many people starting with CocoaPods seem to think pod install is only used the first time
you setup a project using CocoaPods and pod update is used afterwards. But that's not the
case at all.
• Use pod install to install new pods in your project. Even if you already have a
Podfile and ran pod install before; so even if you are just adding/removing pods to a
project already using CocoaPods.
• Use pod update [PODNAME] only when you want to update pods to a newer
version.
This is to be used the first time you want to retrieve the pods for the project, but also every
time you edit your Podfile to add, update or remove a pod.
• Every time the pod install command is run — and downloads and install new pods
— it writes the version it has installed, for each pods, in the Podfile.lock file. This
file keeps track of the installed version of each pod and locks those versions.
• When you run pod install, it only resolves dependencies for pods that are not already
listed in the Podfile.lock.
◦ For pods listed in the Podfile.lock, it downloads the explicit version listed in
the Podfile.lock without trying to check if a newer version is available
◦ For pods not listed in the Podfile.lock yet, it searches for the version that
matches what is described in the Podfile (like in pod 'MyPod', ‘~>1.2')
When you run pod outdated, CocoaPods will list all pods which have newer versions than
the ones listed in the Podfile.lock (the versions currently installed for each pod). This means
that if you run pod update PODNAME on those pods, they will be updated — as long as the
new version still matches the restrictions like pod 'MyPod', '~>x.y' set in your Podfile.
pod repo update
Updates the local clone of the spec-repo NAME. If NAME is omitted this will update all
spec-repos in /Users/dimitris/.cocoapods/repos.
27- Name the framework that is used to construct application’s user interface for iOS.
The UIKit framework is used to develop application’s user interface for iOS. UIKit
framework provides event handling, drawing model, windows, views, and controls
specifically designed for a touch screen interface.UIKit classes should be used only from
an application’s main thread. Note: The derived classes of UIResponder and the classes
which manipulate application’s user interface should be used from application’s main
thread.The UIKit infrastructure takes care of delivering events to custom objects. As an app
developer, you have to override methods in the appropriate objects to process those events.
git show [commit] : shows the metadata and content changes of the specified commit
git tag [commitID] : used to give tags to the specified commit
git checkout [branch name] : used to switch from one branch to another
git checkout -b [branch name] : creates a new branch and also switches to it
The following steps will resolve conflict in Git-
1. Identify the files that have caused the conflict.
2. Make the necessary changes in the files so that conflict does not arise again.
3. Add these files by the command git add.
4. Finally to commit the changed file using the command git commit
29- Which API is used to write test scripts that help in exercising the
application’s user interface elements and Do you have TDD experience? How
do you unit and UI test on iOS?
UI Automation API is used to automate test procedures. Tests scripts are written in
JavaScript to the UI Automation API. This in turn simulates user interaction with the
application and returns log information to the host computer.Even though, historically, the
iOS community wasn’t big on TDD, it is now becoming more popular thanks to
improvements in tooling and influence from other communities, such as Ruby, that
embraced TDD a long time ago.TDD is a technique and a discipline where you write
failing tests first before you write production code that makes them pass. The tests drive
implementation and design of your production code, helping you write only the code
necessary to pass the tests implementation, no more, no less. The discipline could be
daunting at first and you don’t see payoff of that approach immediately, but if you stick to
it, it helps you move faster in the long run. It is especially effective at helping you with
refactoring and code changes because at any given time you have the safety net of your
tests to tell you if something broke or if everything is still working fine as you change
things.
Recently Apple made improvements to XCTest frameworks to make testing easier for us.
They also made a lot of improvements with UI testing in Xcode (XCUITest), so now we
have a nice programmatic interface to interact with our apps and query things we see on the
screen. Alternatively you could go with frameworks like KIF, iOSSnapshotTestCase,
EarlGrey.
In regards to unit testing, there are several options as well, but the two most popular ones
are XCTest and Quick and Nimble.
XCTest is a xUnit like testing framework built by Apple. This is what they recommend to
use, and it has the best integration with Xcode.
Quick is a Spec-like BDD framework that helps you describe your specs/tests in terms of
behaviour rather than “tests.” Fans of Spec like it a lot.
Nimble is a matcher library that can be used with XCTest or Quick to assert expectations in
your tests/specs.
More and more teams and companies embrace TDD, and it has become a vital part of the
iOS development process. If you don’t want to be left behind, get on board with it and learn
how to test-drive your code.
As testing becomes a more prominent and important practice in the iOS world, it’s
important to know what you’re doing as you write your tests. Your test code is as important
as your application code. This question gauges your understanding of testing terminology
for objects used to aid in unit-testing.
There are various ways different people call and categorise test objects but most commonly
test objects can be categorised in the following way: fakes, stubs, and mocks.
Fakes is the general umbrella term for any kind of mock, fake, stub, double, etc. On their
own, they typically have no implementation and only fulfil the interface API requirements
of the types they are substituting.
Stubs are fakes that do some meaningful work that’s necessary for the objects involved in a
test to operate, but not used for anything more than that. They can’t be used in place of real
production objects but can return stubbed values. They can’t be asserted on.
Mocks are fakes that can be asserted on. Mocks are used in place of other objects just like a
fake, but they themselves record some data such as the number of method calls or variables
passed for your test to assert on later.
Many developers make a mistake of calling any test object a mock, but there is a specific
distinct nomenclature for test objects that indicates the purpose for each one. As a senior
developer you’re not merely writing tests, you also should know how to maintain them as
well as your application codebase.
30-SSL Pinning in iOS and how would you securely store private user data offline on a
device? What other security best practices should be taken?
There are many popular options to perform SSL pining in iOS. These are- URLSession,
AlamoFire, AFNetworking, TrustKit. We can implement Certificate pinning as well as
public-key pining.
Why Do You Need SSL Certificate Pinning?
SSL pinning allows the application to only trust the valid or pre-defined certificate or Public
Key. The application developer uses SSL pinning technique as an additional security layer
for application traffic. As normally, the application trusts custom certificate and allows the
application to intercept the traffic.
Restricting the set of trusted certificates through pinning prevents attackers from analysing
the functionality of the app and the way it communicates with the server.
How SSL works?
• Client machine sends a connection request to server, server listens the request.
• Server gives response including public key and certificate.
• Client checks the certificate and sends a encrypted key to server.
• Server decrypt the key and sends encrypted data back to the client machine.
• Client receives and decrypt the encrypted data.
Types of SSL Pinning(What to Pin)?
• Pin the certificate: You can download the server’s certificate and put this in your app
bundle. At runtime, the app compares the server’s certificate to the one you’ve
embedded.
• Pin the public key: You can retrieve the certificate’s public key and include it in your
code as a string. At runtime, the app compares the certificate’s public key to the one
hard-coded hash string in your code.
Again there is no right answer to this, but it's a great way to see how much a person has dug
into iOS security. If you're interviewing with a bank I'd almost definitely expect someone to
know something about it, but all companies need to take security seriously, so here's the
ideal list of topics I'd expect to hear in an answer:
• If the data is extremely sensitive then it should never be stored offline on the device
because all devices are crackable.
• The keychain is one option for storing data securely. However it's encryption is
based on the pin code of the device. User's are not forced to set a pin, so in some
situations the data may not even be encrypted. In addition the users pin code may be
easily hacked.
• A better solution is to use something like SQLCipher which is a fully encrypted
SQLite database. The encryption key can be enforced by the application and separate
from the user's pin code.
Other security best practices are:
• Only communicate with remote servers over SSL/HTTPS.
• If possible implement certificate pinning in the application to prevent man-in-the-
middle attacks on public WiFi.
• Clear sensitive data out of memory by overwriting it.
• Ensure all validation of data being submitted is also run on the server side.
struct employee:Codable
{
let name:String
let state:String
let zip:String
let area:String
case name
case state
case zip = "zip_code"
case area
let encoder=JSONEncoder()
if let jsondata=try? encoder.encode(names), let jsonString=String(data: jsondata,
encoding: .utf8)
{
print(jsonString)
}
You can integrate SwiftLint into the development process and show you how to set up in
your local machine and Jenkins server to run the SwiftLint automatically.
36-What is Jenkins?
Jenkins is a free open source Continuous Integration tool and automation server to monitor
continuous integration and delivery. It is written in Java.
It is known as an automated Continuous Delivery tool that helps to build and test the
software system with easy integration of changes to the system. Jenkins follows Groovy
Scripting.
Also, it enables developers to continuously check in their code and also analyse the post-
build actions. The automation testers can use to run their tests as soon as the new code is
added or code is modified.
Jenkins is used to continuously monitor the large code base in real-time. It enables
developers to find bugs in their code and fix them. Email notifications are made to the
developers regarding their check-ins as a post-build action.
Advantages of Jenkins are as follows:
• Build failures are cached during the integration stage.
• Notifies the developers about build report status using LDAP (Lightweight Directory
Access Protocol) mail server.
• Maven release project is automated with simple steps.
• Easy bug tracking.
• Automatic changes get updated in the build report with notification.
• Supports Continuous Integration in agile development and test-driven development.
(It involves keeping the latest copy of the source code at a commonly shared hub where all
the developers can check to fetch out the latest change in order to avoid conflict.)
Continuous Delivery:
Why Jenkins is being called as a Continuous Delivery Tool:
1. Developers work on their local environment for making changes in the source code
and push it into the code repository.
2. When a change is detected, Jenkins performs several tests and code standards to
check whether the changes are good to deploy or not.
3. Upon a successful build, it is being viewed by the developers.
4. Then the change is deployed manually on a staging environment where the client
can have a look at it.
5. When all the changes get approved by the developers, testers, and clients, the final
outcome is saved manually on the production server to be used by the end-users of
the product.
In this way, Jenkins follows a Continuous Delivery approach and is called the
Continuous Delivery Tool.
traits include hardware features such as the range of colours supported by the device display
(also referred to as the display gamut) and whether or not the device supports features such
as 3D Touch. The traits of a device that are dictated by user configuration include the
dynamic type size setting and whether the device is configured for left to right or right to
left text direction.
Arguably the most powerful trait category, however, relates specifically to the size and
orientation of the device screen. These trait values are referred to as size classes. Size
classes categorise the various screen areas that an application user interface is likely to
encounter during execution. Rather than represent specific screen dimensions and
orientations, size classes represent width (w) and height (h) in terms of being compact (C)
or regular (R).
Both the iPhone 7 and iPhone 7 Plus devices in portrait orientation, for example, are
represented by the compact width and regular height size class (wC hR). When the iPhone 7
{a1, a2, a3, a4, a5} and branch (b) has a list of commits {b1, b2, b3, b4, b5}, then after
merging them the result might be something like:
> a1, b1, a2, a3, b3, b4, b5, a5 (mixed together),
while after rebasing (b) over (a) the list will necessarily look like:
> a1, a2, a3, a4, a5, b1, b2, b3, b4, b5. (one branch after the other)
If (b) is your feature branch and (a) is your stable master, this is much preferable because
logically you want all of (b)'s commits after (or in git-speak, 'rebased on') the commit's on
(a)'s.
Both Git merge and Git rebase are used to combine the work of two branches together. Only
the techniques of combining is different.
Consider an example to understand the difference between these two techniques:
Let's say that you have two branches in your Git repo viz. master and feature, where the
feature branch is being used to develop something additional & master branch is your
production quality code branch or main branch.
After you are done developing the feature branch, you want to combine it with the master
branch.
If you Git merge it into master, it will combine the tasks of feature into master by creating a
single new commit at the tip of master.
On the other hand, if you Git rebase it, it will place the entire commit history of the feature
branch on the tip of master. It means that your entire feature branch will be reattached to the
tip of master and it will look like a linear sequence of commits.
However, there is a little rule to remember:
Combining tasks from public branch into local branch -- use git rebase
Combining tasks from local branch to public branch -- use git merge
Both Merge and Rebase have their pros and cons. Merge keeps the history of the repository
but can make it hard for someone to understand and follow what’s going on at a particular
stage when there are multiple merges. Rebase on the other hand ‘rewrites’ history (read -
creates new history) but makes the repo look cleaner and is much easier to look at.
What you want to use depends on your need. A lot of companies make merges mandatory
when adding stuff to master branch because they want to see the history of all changes. And
a few companies/Open source projects mandate rebasing as it keeps the flow simple and
easy to follow. Use the one that suits your workflow.
Software Framework - a compiled set of code that accomplishes a task... hence, you can
actually have a static framework or a dynamic framework, which are typically just the
compiled versions of the above.
Hence on iOS, your only option is basically to use a static library or static framework (the
main difference being that a static framework is distributed as a compiled .a file most often,
whereas a static library may simply be included as a subproject - you can see all of the code
- which is compiled first and its resulting .a file used as a dependency by the project).
Now that we're clear(er) on these terms, setting up a static library and supporting media
bundle for iOS isn't too difficult, and there are many tutorials on how to do such. I
personally would recommend this one:
https://github.com/jverkoey/iOS-Framework
This is a pretty straight-forward guide and doesn't have the disadvantage of dealing with
"fake static libraries"... check it out for more info...
Once you've created your static library, it's as easy as including it as a submodule within Git
for use across different projects.
As of iOS 8, Apple now permits developers to create dynamic frameworks! (Note: your app
must have a minimum target of iOS 8 to include a dynamic framework... back porting isn't
allowed.)
This has been added as a new project template. In Xcode 6.1, this can be found at:
New Project -> iOS -> Framework & Library -> Cocoa Touch Framework
46- Common reasons for app rejection from App store review process?
• Broken Links:
There are a couple of needed links as a part of the App Store application method. For
example, your app must have a link to your privacy policy. You’ve additionally ought to
have a link to app support in order that users will contact you. If these links don’t go
anyplace, your app is rejected. Make sure these pages square measure in operating order
before submission.
• Bugs throughout the review method
Obviously, you wouldn’t need an automobile you were pondering shopping for to interrupt
down on the check drive. That’s an excellent thanks to making sure that the automobile isn’t
going get oversubscribed. By that very same token, a bug that rears its ugly head
throughout the review method can place your app on the main road to rejection. Each app
goes to possess some problems once it’s initial free, however, try and catch as several as
available throughput testing to avoid rejections and delays.
• Crashes throughout the review method
Moment dismissal anticipates your application on the off chance that it crashes all through
the review technique. Obviously, the App Store is trying to find apps that truly work. If they
don’t, they’re obtaining thrown the “no” pile.
• Long loading times
Your app has precisely fifteen seconds to load, or Apple goes to reject it. you'll reduce your
app load time by ensuring any pictures used square measure the adequate measure and
prioritising any bugs that reason the application to crash after loading. For a lot of insight in
decreasing load times, examine this text on important. measure and prioritising any bugs
that reason the application to crash after loading.
• Poor interface
Apps on the app store should supply worth and value to finish users. Apple is explicit
regarding the top quality of its applications. Look to satisfy the high-level style demand of
Apple, just as content size, content configuration, differentiate, arrangement, goals,
mutilation, hit controls, association, and so forth. Cohesive user expertise is essential to
obtain through the App Store.
• Apps that square measure demos or in beta
Demos aren’t happy with the Apple App Store. Words like “demo,” “test” and “beta” square
measure reaching to get flagged for rejection as a result of the App Store needs final
versions of apps. This is often simply inevitable and best observe anyway. You don’t wish
users are downloading associate imperfect version of your app.
• Mistreatment non-public API
Apple is that the sole guy on the block which will use a private API. ALL Apple apps have
to be compelled to use a public API so as to create it through the approval method. The
rationale is that Apple needs to make sure that public arthropod genus square measure in
use is to shield user knowledge from being abused.
• Inappropriate ad identifiers
Ads square measure a part of the method of building a lot of apps, however, if you utilise
IDFA (the iOS advertising identifier) on something that isn’t an advertisement, then you’re
reaching to get rejected right away.
• Unrelated keywords
Keywords square measure; however, users notice your app. However, mistreatment
keywords that square measure incorrect or square measure unrelated to the particular
mobile application square measure cause for fast rejection from Apple. It’s not legal to use
proprietary words, or titles that square measure deceptive. Apps got to gift themselves
honestly so as to create it through the app store approval method.
• Inappropriate content
Gambling and creative activity don't seem to be allowed within the App Store.
• Combination content
Content in mobile apps is supposed to be distinctive. Apps that square measure merely
aggregates of content which will be found elsewhere square measure the net goes to induce
kicked out by Apple. What goes informed any Apple application should be content that’s
usable and original for finish users. Plagiarism and aggregation can get your app showed
within the blink of a watch.
• Offensive language
Apple is supposed to be a secure area for folks of all non-secular faiths, ages, orientations,
etc. It’s ought to all be clean and on top of the board. Something that's meant to arouse
anger or to elicit a violent reaction can get thrown out right away.
• No privacy policy
It’s a tough and quick demand that each Apple app has a privacy policy in situ so as to
induce approval.
• Sharing personal user knowledge
Any app that shares personal user knowledge, from names to photos to contact info, are
rejected. Privacy could be a massive deal to Apple, and they’ve created a large quantity of
trust with users so as to spice up their whole and create the foremost out of their client
loyalty. Incursive privacy is simply not allowed.
• mistreatment Apple Pay while not the privacy policy
Another privacy policy issue is mistreatment Apple Pay while not the privacy policy for it.
That features any of the weather of stigmatisation or the interface generally.
• Missing information
A major demand for apps within the Apple Store is that they need information. Meaning as
well as screenshots, descriptions, etc. If the information isn’t there, then the app goes to
induce rejected.
@implementation CustomObject
- (void) someMethod {
NSLog(@"SomeMethod Ran");
}
@end
Step 5: The next step is to add Class to Bridging-Header
In YourProject-Bridging-Header.h
#import "CustomObject.h"
Step 6: At last, use your Object
In SomeSwiftFile.swift:
var instanceOfCustomObject: CustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello World"
println(instanceOfCustomObject.someProperty)
instanceOfCustomObject.someMethod()
In the bridging header, there is no need to import explicitly.
50-Apart from incorporating views and controls, what else an app can
incorporate?
Apart from incorporating views and controls, an app can also incorporate Core Animation
layers into its view and control hierarchies.Layer objects are data objects which represent
visual content. Layer objects are used by views to render their content. Custom layer
objects can also be added to the interface to implement complex animations and other
types of sophisticated visual effects.
54-Which are the protocols used in table view and What is the reuseIdentifier used
for?
Table view contain two delegate protocols
(1) Uitable view data source
(2).Uitable view delegate.
ui view table view data source three method namely (1)No of sections.
(2)No of rows in sections.
(3)Cell for row index path row.
In ui table view delegate contain (1)Did select row at index path row
The reuseIdentifier is used to indicate that a cell can be re-used in a UITableView. For
example when the cell looks the same, but has different content. The UITableView will
maintain an internal cache of UITableViewCell’s with the reuseIdentifier and allow them to
be re-used when dequeueReusableCellWithIdentifier: is called. By re-using table cell’s the
scroll performance of the tableview is better because new views do not need to be created.
55-What options do you have for implementing storage, database and persistence on
iOS?
Interviewers ask this question to grasp your understanding of what tools and ways you have
available to store and persist data on iOS.
Generally there are the following ways to store data in order from simple to complex:
In-memory: arrays, dictionaries, sets, and other data structures are perfectly fine for storing
data intermediately or if it doesn’t have to be persisted.
NuserDefaults: If user removed the app from device the saved UserName and Password
also removed.
Keychain: If user removed the app from device the saved UserName and Password still is
there
Plist: Property lists organise data into named values and lists of values using several object
types. These types give you the means to produce data that is meaningfully structured,
transportable, storable, and accessible, but still as efficient as possible. Property lists are
frequently used by applications running on both Mac OS X and iOS. The property-list
programming interfaces for Cocoa and Core Foundation allow you to convert hierarchically
structured combinations of these basic types of objects to and from standard XML. You can
save the XML data to disk and later use it to reconstruct the original objects.The user
defaults system, which you programmatically access through the NSUserDefaults class,
uses property lists to store objects representing user preferences. This limitation would
seem to exclude many kinds of objects, such as NSColor and NSFont objects, from the user
default system. But if objects conform to the NSCoding protocol they can be archived to
NSData objects, which are property list–compatible objects.
File/disk storage: is a way of writing data (serialised or not) to/from a disk using
NSFileManager.
Core Data/Realm: are frameworks that simplify work with databases.
SQLite: is a relational database and is good when you need to implement complex
querying mechanics and Core Data or Realm won’t cut it.
Below is the sqlite methods:
sqlite3_open, sqlite3_prepare_v2, sqlite3_step, sqlite3_finalize, sqlite3_close, sqlite3_ok,
sqlite3_row
You should know different ways store data on iOS and their advantages or disadvantages.
Don’t limit yourself to only one solution that you’re used to (like Core Data, for example).
Know when one is preferable over the other.
56-What is the major purposes of Frameworks and tell four frameworks used in
iPhone?
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.
(1)Ui kit framework
(2)Map kit framework
Alternatively, you could take a completely radical approach, which is to use different
technology like ASDK (Texture). ASDK (Texture) is made specifically for list views with
dynamic content size and is optimised to calculate cell heights in a background thread,
which makes it super performant.Yes, we can use two tableviews on the same view
controllers and you can differentiate between two by assigning them tags...or you can also
check them by comparing their memory addresses.Yes. We can conditionally bind
tableviews with two different data sources.
For Int :
var x = 5
var y = 7
x=x+y
y=x-y
x=x-y
print(x)
print(y)
61-Determine the value of “x” in the Swift code below. Explain your answer.
var a1 = [1, 2, 3, 4, 5]
var a2 = a1
a2.append(6)
var x = a1.count
In Swift, arrays are implemented as structs, making them value types rather than reference
types (i.e., classes). When a value type is assigned to a variable as an argument to a function
or method, a copy is created and assigned or passed. As a result, the value of “x” or the
count of array “a1” remains equal to 5 while the count of array “a2” is equal to 6,
appending the integer “6” onto a copy of the array “a1.” The arrays appear in the box
below.
a1 = [1, 2, 3, 4, 5]
a2 = [1, 2, 3, 4, 5, 6]
64-The following code snippet results in a compile time error and explain mutating
function:
struct IntStack {
var items = [Int]()
func add(x: Int) {
items.append(x) // Compile time error here.
}
}
Explain why a compile time error occurs. How can you fix it?
Answer: Structures are value types. By default, the properties of a value type cannot be
modified from within its instance methods.
However, you can optionally allow such modification to occur by declaring the instance
methods as ‘mutating’; e.g.:
struct IntStack {
var items = [Int]()
mutating func add(x: Int) {
items.append(x) // All good!
}
}
There are three main aspects of App Thinning: App Slicing, Bitcode, and On Demand
Resources.
App Slicing:
“Slicing is the process of creating and delivering variants of the app bundle for different
target devices.
A variant contains only the executable architecture and resources that are needed for the
target device.” In other words, App Slicing delivers only relevant assets to each device
(depending on screen resolution, architecture, etc.) In fact, app slicing handles the majority
of the app thinning process.But must use Xcode 7 as it contains the iOS 9 SDK with
support for app thinning.
On Demand Resources are files that can be downloaded after the app’s first installation.
For example, specific levels of a game (and these levels’ associated content) could be
downloaded only when the player has unlocked them. Further, earlier levels that the player
has not engaged with after a certain set time can be removed to save storage on the device.
Bitcode:
Bitcode makes apps as fast and efficient as possible on whatever device they’re running.
Bitcode automatically compiles the app for the most recent compiler and optimises it for
specific architectures (i.e. arm64 for 64 bit processors such as the iPhone 6s and iPad Air
2).
Application Kit: is a framework containing all the objects you need to implement your
graphical, event-driven user interface: windows, panels, buttons, menus, scrollers, and text
fields. The Application Kit handles all the details for you as it efficiently draws on the
screen, communicates with hardware devices and screen buffers, clears areas off the
screen before drawing, and clips views.
You also have the choice at which level you use the Application Kit:
· Use Interface Builder to create connections from user interface objects to your application
objects.
· Control the user interface programmatically, which requires more familiarity with
AppKit classes and protocols.
· Implement your own objects by subclassing NSView or other classes.
·
67-Selectors, Dynamic and Static Typing.
Selector: has two meanings. It can be used to refer simply to the name of a method when
it’s used in a source-code message to an object. It also, though, refers to the unique
identifier that replaces the name when the source code is compiled. Compiled selectors are
of type SEL. All methods with the same name have the same selector. You can use a
selector to invoke a method on an object this provides the basis for the implementation of
the target-action design pattern in Cocoa.
Static typed: languages are those in which type checking is done at compile-time.
Dynamic typed: languages are those in which type checking is done at run-
time.Objective-C is a dynamically-typed language, meaning that you don’t have to tell
the compiler what type of object you’re working with at compile time. Declaring a
type for a variable is merely a promise which can be broken at runtime if the code
leaves room for such a thing. You can declare your variables as type id, which is
suitable for any Objective-C object.
68-What are design patterns besides common Cocoa patterns that you know?
This is an advanced question that an interviewer will ask when you interview for a senior or
architect position. The expectation is that you know more practical design patterns used in
iOS apps beyond the basic ones covered in the earlier question. Be ready to recall a bunch
of Gang of Four patterns and other similar patterns.
Design patterns are a huge topic on their own (they are covered better in my book), so here
I’ll only summarise those I see commonly in iOS code bases.
Besides commonly used MVC, Singleton, Delegate, and Observer patterns, there are many
others that are perfectly applicable in iOS applications: Factory Method, Adapter,Decorator,
Command, and Template.
Factory Method is used to replace class constructors, too abstract and hide objects
initialisation so that the type can be determined at runtime, and to hide and contain switch/if
statements that determine the type of object to be instantiated.
Adapter is a design pattern that helps you, as the name suggests, adapt the interface of one
object to the interface of another. This pattern is often used when you try to adapt third-
party code that you can’t change to your code, or when you need to use something that has
an inconvenient or incompatible API.
Decorator is a wrapper around another class that enhances its capabilities. It wraps around
something that you want to decorate, implements its interface, and delegates messages sent
to it to the underlying object or enhances them or provides its own implementation.
Command is a design pattern where you’d implement an object that represents an
operation that you would like to execute. That operation can have its own state and logic to
perform the task it does. The main advantages of this design pattern are that you can hide
internal implementation of the operation from the users, you can add undo/redo capabilities
to it, and you can execute operations at a later point in time (or not at all) instead of right
away where the operation was created.
Template is a design pattern where the main concept is to have a base class that outlines the
algorithm of what needs to be done. The base class has several abstract methods that are
required to be implemented by its concrete subclasses. These methods are called hook
methods. Users of the Template Method classes only interact using the base class that
implements the algorithm steps; concrete implementations of those steps are supplied by
subclasses.
Sticking only to MVC, Singleton, Delegate, and Observer patterns is fine when you’re just
starting with the iOS platform, but for advanced things you need to reach deeper into more
abstract and high-level stuff like Gang of Four OOP Design Patterns. They are very useful
and make your codebase more flexible and maintainable.
69-Class Introspection
· Determine whether an objective-C object is an instance of a class
[obj isMemberOfClass:someClass];
· Determine whether an objective-C object is an instance of a class or its
descendants
[obj isKindOfClass:someClass];
· The version of a class
[MyString version]
· Find the class of an Objective-C object
· Verify 2 Objective-C objects are of the same class
[obj1 class] == [obj2 class]
·
70- Proxy
As long as there aren’t any extra instance variables, any subclass can proxy itself as its
superclass with a single call. Each class that inherits from the superclass, no matter where it
comes from, will now inherit from the proxied subclass. Calling a method in the superclass
will actually call the method in the subclass. For libraries where many objects inherit from
a base class, proxying the superclass can be all that is needed.
71- Why category is better than inheritance?
Objective c subclass can derived from a single parent class.It is called “single
inheritance”
If category is used, you can use same class, no need to remember a new class-name.
Category created on a base class is available on sub classes.
76-Coredata
To demonstrate this, we’re going to build two Core Data entities: one to track candy bars,
and one to track countries where those bars come from.
Relationships come in four forms:
• A one to one relationship means that one object in an entity links to exactly one
object in another entity. In our example, this would mean that each type of candy has
one country of origin, and each country could make only one type of candy.
• A one to many relationship means that one object in an entity links to many objects
in another entity. In our example, this would mean that one type of candy could have
been introduced simultaneously in many countries, but that each country still could
only make one type of candy.
• A many to one relationship means that many objects in an entity link to one object in
another entity. In our example, this would mean that each type of candy has one
country of origin, and that each country can make many types of candy.
• A many to many relationship means that many objects in an entity link to many
objects in another entity. In our example, this would mean that one type of candy had
been introduced simultaneously in many countries, and each country can make many
types of candy.
NSManagedObject represents a single object stored in Core Data; you must use it to create,
edit, save and delete from your Core Data persistent store. As you’ll see shortly,
NSManagedObject is a shape-shifter. It can take the form of any entity in your Data Model,
appropriating whatever attributes and relationships you defined.
This is where Core Data kicks in! Here’s what the code does:
1 Before you can save or retrieve anything from your Core Data store, you first need to
get your hands on an NSManagedObjectContext. You can consider a managed object
context as an in-memory “scratchpad” for working with managed objects.
Think of saving a new managed object to Core Data as a two-step process: first, you
insert a new managed object into a managed object context; then, after you’re happy
with your shiny new managed object, you “commit” the changes in your managed
object context to save it to disk.
Xcode has already generated a managed object context as part of the new project’s
template. Remember, this only happens if you check the Use Core Data checkbox at
the beginning. This default managed object context lives as a property of the
NSPersistentContainer in the application delegate. To access it, you first get a
reference to the app delegate.
2 You create a new managed object and insert it into the managed object context. You
can do this in one step with NSManagedObject’s static method:
entity(forEntityName:in:).
You may be wondering what an NSEntityDescription is all about. Recall earlier,
NSManagedObject was called a shape-shifter class because it can represent any
entity. An entity description is the piece linking the entity definition from your Data
Model with an instance of NSManagedObject at runtime.
3 With an NSManagedObject in hand, you set the name attribute using key-value
coding. You must spell the KVC key (name in this case) exactly as it appears in your
Data Model, otherwise your app will crash at runtime.
4 You commit your changes to person and save to disk by calling save on the managed
object context. Note save can throw an error, which is why you call it using the try
keyword within a do-catch block. Finally, insert the new managed object into the
people array so it shows up when the table view reloads.
1 Before you can do anything with Core Data, you need a managed object context.
Fetching is no different! Like before, you pull up the application delegate and grab a
reference to its persistent container to get your hands on its
NSManagedObjectContext.
2 As the name suggests, NSFetchRequest is the class responsible for fetching from
Core Data. Fetch requests are both powerful and flexible. You can use fetch requests
to fetch a set of objects meeting the provided criteria (i.e. give me all employees
living in Wisconsin and have been with the company at least three years), individual
values (i.e. give me the longest name in the database) and more.
Fetch requests have several qualifiers used to refine the set of results returned. For
now, you should know NSEntityDescription is a required one of these qualifiers.
Setting a fetch request’s entity property, or alternatively initialising it with
init(entityName:), fetches all objects of a particular entity. This is what you do here
to fetch all Person entities. Also note NSFetchRequest is a generic type. This use of
generics specifies a fetch request’s expected return type, in this case
NSManagedObject.
3 You hand the fetch request over to the managed object context to do the heavy
lifting. fetch(_:) returns an array of managed objects meeting the criteria specified by
the fetch request.
When we talk about persistent data, people probably think of database. If you are familiar
with Oracle or MySQL, you know that relational database stores data in the form of table,
row and column, and it usually facilitates access through what-so-called SQL query.
However, don’t mix up Core Data with database. Though SQLite database is the default
persistent store for Core Data on iPhone, Core Data is not a relational database. It is
actually a framework that lets developers store (or retrieve) data in database in an object-
oriented way. With Core Data, you can easily map the objects in your apps to the table
records in the database without even knowing any SQL.
Managed Object Model – It describes the schema that you use in the app. If you have a
database background, think of this as the database schema. However, the schema is
represented by a collection of objects (also known as entities). In Xcode, the Managed
Object Model is defined in a file with the extension .xcdatamodeld. You can use the visual
editor to define the entities and their attributes, as well as, relationships.
Persistent Store Coordinator – SQLite is the default persistent store in iOS. However,
Core Data allows developers to setup multiple stores containing different entities. The
Persistent Store Coordinator is the party responsible to manage different persistent object
stores and save the objects to the stores. Forget about it you don’t understand what it is.
You’ll not interact with Persistent Store Coordinator directly when using Core Data.
Managed Object Context – Think of it as a “scratch pad” containing objects that interacts
with data in persistent store. Its job is to manage objects created and returned using Core
Data. Among the components in the Core Data Stack, the Managed Object Context is the
one you’ll work with for most of the time. In general, whenever you need to fetch and save
objects in persistent store, the context is the first component you’ll talk to.
NSSQLiteStoreType: This is the option you most commonly use as it just stores your
database in a SQLite database.
NSXMLStoreType: This will store your data in an XML file, which is slower, but you can
open the XML file and it will be human readable. This has the option of helping you debug
errors relating to storage of data. However, do note that this storage type is only available
for Mac OS X.
NSBinaryStoreType: This occupies the least amount of space and also produces the fastest
speed as it stores all data as a binary file, but the entire database binary need to be able to fit
into memory in order to work properly.
NSInMemoryStoreType: This stores all data in memory and provides the fastest access
speed. However, the size of your database to be saved cannot exceed…
Core Data supports four delete rules:
• No Action
• Nullify
• Cascade
• Deny
80-Collection
Swift uses a standard set of basic data types for different purposes such as Boolean values,
numbers, and strings.
• Int: int is used to store the integer value.
• Double and Float: Double and Float in swift are considered when while working
with the decimal numbers.
Bool: The bool type is used to store the Boolean value. In swift, it uses true and false
•
conditions.
• String: In String literals, the user defines the text that is enclosed by double quotes
in Swift.
• Arrays: Arrays are the collection of list items.
• Dictionaries: A dictionary is an unordered collection of items of a particular type
that is connected with a unique key.
• An array can hold only one type of data, whereas NSArray can hold different types
of data.
• An array is a value type, whereas NSArray is an immutable reference type.
There are three primary collection types that are available in swift for storing a collection of
values. They are dictionaries, sets, and arrays
1. Arrays: Arrays is an ordered collection of values, which is stored in the same type
of values in an ordered list.
2. Sets: Sets are an unordered collection of unique values, which are stored in a distinct
value of the same type in a collection without any defined ordering.
3. Dictionaries: Dictionaries are an unordered collection of Key and value pair
associations in an unordered manner.
In Cocoa and Cocoa Touch, a collection is a Foundation framework class used for storing
and managing groups of objects. Its primary role is to store objects in the form of either
an array, a dictionary, or a set.
@implementation MyCustomController
- (void)viewDidLoad {
CGRect frame = CGRectMake(100, 100, 100, 50);
self.alert = [[UILabel alloc] initWithFrame:frame];
self.alert.text = @"Please wait...";
[self.view addSubview:self.alert];
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
sleep(10);
self.alert.text = @"Waiting over";
}
);
}
@end
All UI updates must be done on the main thread. In the code above the update to the alert
text may or may not happen on the main thread, since the global dispatch queue makes no
guarantees . Therefore the code should be modified to always run the UI update on the main
thread
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
sleep(10);
dispatch_async(dispatch_get_main_queue(), ^{
self.alert.text = @"Waiting over";
});
});
unwrapping of the optional's value. There is a method for avoiding forced unwrapping
which we will cover below.
In Swift, though, there are two ways to cast — one that’s safe and one that’s not .
as used for upcasting and type casting to bridged type
as? used for safe casting, return nil if failed
as! used to force casting, crash if failed. should only be used when we know the
downcast will succeed.
You can use zip to combine your two arrays, and thereafter apply a .flatMap to the tuple
elements of the zip sequence:
add(number:10, number1:20)
Any: can represent an instance of any type at all, including function types and optional
types.
AnyObject: can represent an instance of any class type.
Consider the following code:
var array = [AnyObject]()
struct Test {}
array.append(Test())
This code generates a compilation error, with the following error message:
Type 'Test' does not conform to protocol 'AnyObject'
The failure is obvious because a struct is a value and not a reference type, and as such it
doesn’t implement and cannot be cast to the AnyObject protocol.
struct Test {}
array.append(Test())
The array array is filled in with values of type respectively int, double, string, array and
dictionary. All of them are value types and not reference types, and in all cases no error is
reported by the compiler. Why?
Answer: The reason is that swift automatically bridges:
• number types to NSNumber
• strings to NSString
• arrays to NSArray
• dictionaries to NSDictionary
which are all reference types.
87-Differentiate Foundation vs Core Foundation
Foundation framework: defines a base layer of Objective-C classes. In addition to
providing a set of useful primitive object classes, it introduces several paradigms that
define functionality not covered by the Objective-C language. The Foundation
framework is designed with these goals in mind: · Provide a small set of basic utility
classes.Make software development easier by introducing consistent conventions for
things such as deallocation.Support Unicode strings, object persistence, and object
distribution.Provide a level of OS independence, to enhance portability.
CoreFoundation: is a general-purpose C framework whereas Foundation is a general-
purpose Objective-C framework. Both provide collection classes, run loops, etc, and
many of the Foundation classes are wrappers around the CF equivalents. CF is mostly
open-source , and Foundation is closed-source.
Core Foundation is the C-level API, which provides CFString, CFDictionary and the
like.Foundation is Objective-C, which provides NSString, NSDictionary, etc.
CoreFoundation is written in C while Foundation is written in Objective-C. Foundation
has a lot more classes CoreFoundation is the common base of Foundation and Carbon.
88- Readers-Writers
Multiple threads reading at the same time while there should be only one thread writing.
The solution to the problem is a readers-writers lock which allows concurrent read-only
access and an exclusive write access. Terminology;
Race Condition A race condition occurs when two or more threads can access
shared data and they try to change it at the same time.
Deadlock A deadlock occurs when two or sometimes more tasks wait for the other to
finish, and neither ever does.
Readers-Writers problem Multiple threads reading at the same time while there
should be only one thread writing.
Readers-writer lock Such a lock allows concurrent read-only access to the shared
resource while write operations require exclusive access.
Dispatch Barrier Block Dispatch barrier blocks create a serial-style bottleneck
when working with concurrent queues.
89-Retain cycle or Retain loop.
Retain cycle:
The book has a strong reference to its pages and the page has a strong reference to the
book? Guess what happens next. That’s right, a memory leak.
A memory leak occurs when a content remains in memory even after its lifecycle has
ended.
In this case, the memory leak is caused by two strong variables that address each other. This
problem is known as the retain cycle problem.
Ok, now let’s see some solutions.
Just remember that now the book will be an optional and eventually it could become nil.
//Memoey Leak
class A
{
var b:B!
deinit
{
print("deinit of A")
}
}
class B
{
var a:A!
deinit
{
print("deinit of B")
}
}
do {
let a = A()
let b = B()
a.b = b
b.a = a
}
Retain loop: Objective-C’s garbage collector (when enabled) can also delete retain-
loop groups but this is not relevant on the iPhone, where Objective-C garbage
collection is not supported.
90-What’s your preference when writing UI’s, Xib files, Storyboards or programmatic
UIView?
There's no right or wrong answer to this, but it's great way of seeing if you understand the
benefits and challenges with each approach. Here's the common answers I hear:
• Storyboard's and Xib's are great for quickly producing UI's that match a design spec.
They are also really easy for product managers to visually see how far along a screen
is.
• Storyboard's are also great at representing a flow through an application and
allowing a high-level visualisation of an entire application.
• Storyboard's drawbacks are that in a team environment they are difficult to work on
collaboratively because they're a single file and merge's become difficult to manage.
• Storyboards and Xib files can also suffer from duplication and become difficult to
update. For example if all button's need to look identical and suddenly need a colour
change, then it can be a long/difficult process to do this across storyboards and xibs.
• Programmatically constructing UIView's can be verbose and tedious, but it can allow
for greater control and also easier separation and sharing of code. They can also be
more easily unit tested.
Most developers will propose a combination of all 3 where it makes sense to share code,
then re-usable UIViews or Xib files.
The main thread loop creates an autorelease pool at the beginning of the function, and
release it at the end. This establishes a pool for the lifetime of the task. However, this also
means that any autoreleased objects created during the lifetime of the task are not disposed
of until the task completes. This may lead to the task’s memory footprint increasing
unnecessarily.
Ball *ball = [[[[Ball alloc] init] autorelease] autorelease];
It will crash because it’s added twice to the autorelease pool and when it it dequeued
the autorelease pool calls release more than once.
1. If you are writing a program that is not based on a UI framework, such as a
command-line tool.
2.If you write a loop that creates many temporary objects.You may create an
autorelease pool inside the loop to dispose of those objects before the next iteration.
Using an autorelease pool in the loop helps to reduce the maximum memory
footprint of the application.
3. If you spawn a secondary thread.
The strong and weak are new ARC types replacing retain and assign
respectively.
Strong: reference is a reference to an object that stops it from being
deallocated. In other words it creates an owner relationship, strong is
the default so you don’t need to type it. This means any object created
using alloc/init is retained for the lifetime of its current scope. The
“current scope” usually means the braces in which the variable is
declared.
Weak: reference is a reference to an object that does not stop it from being
deallocated. In other words, it does not create an owner relationship.Delegates
and outlets should be weak, weak means the object can be destroyed at
anytime. This is only useful if the object is somehow strongly referenced
somewhere else. When destroyed, a variable with weak is set to nil.
A weak reference allows the possibility of it to become nil (this happens automatically
when the referenced object is deallocated), therefore the type of your property must be
optional - so you, as a programmer, are obligated to check it before you use it (basically the
compiler forces you, as much as it can, to write safe code).
unsafe_unretained/unowned weak: is just like weak but the pointer is not set to nil when
the object is deallocated. Instead the pointer is left dangling.
An unowned reference presumes that it will never become nil during its lifetime. An unowned
reference must be set during initialisation - this means that the reference will be defined as a non-
optional type that can be used safely without checks. If somehow the object being referred to is
deallocated, then the app will crash when the unowned reference will be used.
If self could be nil in the closure use [weak self].
If self will never be nil in the closure use [unowned self].
If it's crashing when you use [unowned self] then self is probably nil at some point in that closure
and you probably need to use [weak self] instead.
AutoLayout provides a flexible and powerful layout system that describes how views and
the UI controls calculates the size and position in the hierarchy.AutoLayout is way of laying
out UIViews using a set of constraints that specify the location and size based relative to
other views or based on explicit values. AutoLayout makes it easier to design screens that
resize and layout out their components better based on the size and orientation of a screen.
_Constraint_s include:
• setting the horizontal/vertical distance between 2 views
• setting the height/width to be a ratio relative to a different view
• a width/height/spacing can be an explicit static value
Sometimes constraints conflict with each other. For example imagine a UIView which has 2
height constraints: one says make the UIView 200px high, and the second says make the
height twice the height of a button. If the iOS runtime can not satisfy both of these
constraints then it has to pick only one. The other is then reported as being "broken" by
iOS.
93-A product manager in your company reports that the application is crashing. What
do you do?
This is a great question in any programming language and is really designed to see how you
problem solve. You're not given much information, but some interviews will slip you more
details of the issue as you go along. Start simple:
• get the exact steps to reproduce it.
• find out the device, iOS version.
• do they have the latest version?
• get device logs if possible.
Once you can reproduce it or have more information than start using tooling. Let's say it
crashes because of a memory leak, I'd expect to see someone suggest using Instruments
leak tool. A really impressive candidate would start talking about writing a unit test that
reproduces the issue and debugging through it.
Other variations of this question include slow UI or the application freezing. Again the idea
is to see how you problem solve, what tools do you know about that would help and do you
know how to use them correctly.
Where is the bug? What does this bug cause? What’s the proper way to fix it?
Answer: The second line uses the stringForKey method of NSUserDefaults, which returns
an optional, to account for the key not being found, or for the corresponding value not being
convertible to a string.
During its execution, if the key is found and the corresponding value is a string, the above
code works correctly. But if the key doesn’t exist, or the corresponding value is not a string,
the app crashes with the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
The reason is that the forced unwrapping operator ! is attempting to force unwrap a value
from a nil optional. The forced unwrapping operator should be used only when an optional
is known to contain a non-nil value.
The solution consists of making sure that the optional is not nil before force-unwrapping it:
let userPref = defaults.stringForKey("userPref")
if userPref != nil {
printString(userPref!)
}
An even better way is by using optional binding:
if let userPref = defaults.stringForKey("userPref") {
printString(userPref)
}
Swift is probably most similar in look and feel to Ruby or Python. Though you’ll also
probably recognise some C syntax.
1. Optionals
Optionals are a concept which doesn’t exist in C or Objective-C. They allow functions
which may not always be able to return a meaningful value (e.g. in the event of invalid
input) to return either a value encapsulated in an optional or nil. In C and Objective-C, we
can already return nil from a function that would normally return an object, but we don’t
have this option for functions which are expected to return a basic type such as int, float, or
double.
2. Control Flow
Anyone who’s programmed in C or a C-like language is familiar with the use of curly
braces ({}) to delimit code blocks. In Swift, however, they’re not just a good idea: they’re
the law!
3. Type Inference
Swift introduces type safety to iOS development. Once a variable is declared with a
particular type, its type is static and cannot be changed. The compiler is also smart enough
to figure out (or infer) what type your variables should be based on the values you assign
them.
4. Tuples
Swift supports tuples, values which store groups of other values. Unlike arrays, the values
in a tuple don’t have to all be the same type.
5. String Manipulation
Swift offers huge improvements over Objective-C in terms of string manipulation. For
starters, you don’t have to worry about mutable vs. immutable strings anymore: just declare
your string with var if you want to change it in the future, or with let if you need it to
remain constant.
6. Guard And Defer
We have guard, a new conditional statement which can make this code much more
readable. Guard stops program flow if a condition is not met:
Using defer inside a method means that its work will be executed as the method is exiting.
For example:
override func viewDidLoad() {
super.viewDidLoad()
print("Step 1")
myFunc()
print("Step 5")
}
func myFunc() {
print("Step 2")
defer { print("Step 3") }
print("Step 4")
}
That will print "Step 1", "Step 2", "Step 4", "Step 3", "Step 5" – steps 3 and 4 are switched
because 3 is deferred until the myFunc() method ends, i.e. when it goes out of scope
programmatically.
This scope is effectively anything in braces, { and }, but realistically there are two main
ways you may want to use it: inside a do block and inside a loop.
7. Functional Programming Patterns
Swift incorporates a number of functional programming features, such as map and filter,
which can be used on any collection which implements the CollectionType protocol:
8. Enumerations
In Swift, enumerations are more powerful than they ever were in Objective-C: they can
now contain methods and be passed by value.
9. Functions
Swift’s function syntax is flexible enough to define anything from a simple C-style function
to a complex Objective-C-style method with local and external parameter names.
Every function in Swift has a type, which consists of the function’s parameter types and
return type. This means you can assign functions to variables or pass them as parameters to
other functions:
10. Do Statement
The do statement in Swift allows you to introduce a new scope:
Do statements can also contain one or more catch clauses:
Difference between ‘C’ and ‘Swift’ language is that
Swift
• In a swift, the variable and constants are declared before their use
• You have to use “let” keyword for constant and “var” keyword for variable
• There is no need to end code with semi-colon
• Concatenating strings is easy in swift and allows to make a new string from a mix of
constants, literals, variables, as well as expressions
• Swift does not require to create a separate interface like Objective C. You can define
classes in a single file (.swift)
• Swift enables you to define methods in class, structure or enumeration
• In Swift, you use “ +=” Operator to add an item
Objective-C
• In objective C, you have to declare variable as NSString and constant as int
• In objective C, variable is declared as “ and constant as “
• The code ends with semi-colon
• In objective C, you have to choose between NSMutableString and NSString for
string to be modified.
• For classes, you create separate interface (.h) and implementation (.m) files for
classes
• Objective does not allow this
• In C, you use “addObject”: method of NSMutable array to append a new item to an
array
runtime difference within the scope of your program between the original methods of the
class and the methods added by the category. The methods in the category become part of
the class type and are inherited by all the class’s subclasses.As with delegation, categories
are not a strict adaptation of the Decorator pattern, fulfilling the intent but taking a different
path to implementing that intent. The behaviour added by categories is a compile-time
artefact, and is not something dynamically acquired. Moreover, categories do not
encapsulate an instance of the class being extended.
You may implement categories in your code to extend classes without subclassing or to
group related methods. However, you should be aware of these caveats:
• You cannot add instance variables to the class.
• If you override existing methods of the class, your application may behave
unpredictably.
Subclass in Objective C:
Subclassing in simple words is changing the behaviour of properties or methods of an
existing class or in other words subclassing is inheriting a class and modifying the
methods or properties of super class however you want.
Extensions in Objective C:
Extensions are similar to categories but the need of extension is different.
- Class extensions are often used to extend the public interface with additional private
methods or properties for use within the implementation of the class.
- Extensions can only be added to a class for which you have the source code at compile
time (the class is compiled at the same time as the class extension).
- Extensions will be local to a class file.
Class extensions are similar to categories. The main difference is that with an extension,
the compiler will expect you to implement the methods within your main
@implementation, whereas with a category you have a separate @implementation block.
So you should pretty much only use an extension at the top of your main .m file (the only
place you should care about ivars, incidentally) it’s meant to be just that, an extension.
Usually people will use extensions to hide private information off a class without
exposing them to access from any other class.
subclassing, those subclasses could be used anywhere that the superclass was previously
used.
The Interface Segregation Principle (ISP) says many client-specific interfaces are better
than one general-purpose interface. It also states that no client should be forced to depend
on and implemented methods it does not use. What that means is that when you create
interfaces (protocols) that your classes implement, you should strive for and depend on
abstraction over specificity, but not until it becomes a waste where you have to implement a
bunch of methods your new class doesn’t even use.
The Dependency Inversion Principle (DIP) states, “depend on abstractions, not
concretions.” The best example that showcases this principle is the Dependency Injection
(DI) technique. With the Dependency Injection technique, when you create an object, you
supply and inject all of its dependencies upon its initialisation or configuration rather than
let the object create or fetch/find its dependencies for itself.
SOLID principles are the bedrock of good OOP design. Applying these principles will help
you build better, more maintainable software. It is highly advised to be well versed in them
if you are applying to a senior iOS position.
Equitable: relates too being equal, and “comparable” relates to the comparison
between objects. This is important, because how can we be certain that two complex
objects are the same? In many circumstances, this is something that you should decide.
Comparable: A protocol that can be applied to a type using the relational operators <,
<=, >=, and >
Equitable: A protocol that can be applied to a type to allow value equality
Operand: The value on which an operator is performed
105.What is method swizzling in Objective C and why would you use it?
Method swizzling allows the implementation of an existing selector to be switched at
runtime for a different implementation in a classes dispatch table. Swizzling allows you to
write code that can be executed before and/or after the original method. For example
perhaps to track the time method execution took, or to insert log statements
#import "UIViewController+Log.h"
@implementation UIViewController (Log)
+ (void)load {
static dispatch_once_t once_token;
dispatch_once(&once_token, ^{
SEL viewWillAppearSelector = @selector(viewDidAppear:);
SEL viewWillAppearLoggerSelector = @selector(log_viewDidAppear:);
Method originalMethod = class_getInstanceMethod(self, viewWillAppearSelector);
Method extendedMethod = class_getInstanceMethod(self,
viewWillAppearLoggerSelector);
method_exchangeImplementations(originalMethod, extendedMethod);
});
}
- (void) log_viewDidAppear:(BOOL)animated {
[self log_viewDidAppear:animated];
NSLog(@"viewDidAppear executed for %@", [self class]);
}
@end
107.Property Observers
A property observer observes and responds to changes in a property’s value. With property
observer, we don’t need to reset the controls, every time attributes change.
There are two very appropriately named property observers in Swift: willSet, and didSet.
They are called exactly when you think they would be, right before and right after setting,
respectively. On top of this, they are also implicitly given constants describing the
newValue and oldValue respectively.
• willSet comes with a constant parameter that contains the new value, with the default
name newValue
• didSet comes with a constant parameter that contains the old value, with the default
name oldValue
You can override either of those names, if you wish, but if no name is provided, the defaults
are used.
• One is an initial value which is used to store the initial value or the value or result
returned by the closure from each iteration.
• The other one is a closure which takes two arguments, one is the initial value or the
result from the previous execution of the closure and the other one is the next item in
the collection.
Use Higher order functions where ever possible:
• It improves your swift skills.
• Enhances readability of code.
• More functional programming.
Sort:
let numbers=[4,6,2,5,1,3]
let reverse=numbers.sorted{$0>$1}
print(reverse)
avoid blocking the main thread of the application, which handles user interface and event-
related actions. Threads can also be used to divide a large job into several smaller jobs,
which can lead to performance increases on multi-core computers.The problem with
signals is not what they do, but their behaviour when your application has multiple threads.
In a single-threaded application, all signal handlers run on the main thread. In a
multithreaded application, signals that are not tied to a specific hardware error (such as an
illegal instruction) are delivered to whichever thread happens to be running at the time. If
multiple threads are running simultaneously, the signal is delivered to whichever one the
system happens to pick. In other words, signals can be delivered to any thread of your
application.
Threads are still a good way to implement code that must run in real time
• Dispatch Queues make every attempt to run their tasks as fast as possible but they do
not address the real time constraints
• Threads are low level tool that needs to be managed manually.
• Creating a correct threading solution is difficult.
• Thread synchronisation adds complexity to the project
• Incorrectly implemented threading solution might make the system even worse
• Scalability is an issue when it comes to utilising multiple available cores.
• Object oriented way to encapsulate work that needs to be performed asynchronously
• An Operation object is an instance of NSOperation(abstract) class.
• NSOperation class has two concrete subclasses that can be used as is
• NSInvocationOperation (used to execute a method)
• NSBlockOperation (used for executing one or more blocks concurrently)
• An operation can be executed individually/manually by calling its start method or it
can be added to an OperationQueue.
NSInvocationOperation:
• A class we can use as-is to create an operation object based on an object and selector
from your application.
• We can use this class in cases where we have an existing method that already
performs the needed task. Because it does not require subclassing, we can also use
this class to create operation objects in a more dynamic fashion.
NSBlockOperation:
• A class we use as-is to execute one or more block objects concurrently.
• Because it can execute more than one block, a block operation object operates using
a group semantic; only when all of the associated blocks have finished executing is
the operation itself considered finished.
Grand Central Dispatch: provides queues to which the application can submit tasks in the
form of block objects. The block of code submitted to dispatch queues are executed on a
pool of threads managed by the system. Each task can either be executed synchronously or
asynchronously. In case of synchronous execution the program waits for the execution to be
finished before the call returns. In case of asynchronous call the method call returns
immediately.Dispatch Queues can be serial or concurrent. In case of serial dispatch queues
the work items are executed one at a time and in case of concurrent although the tasks are
dequeued in order but they run in parallel and can finish in any order. Grand Central
Dispatch is ideal if you just need to dispatch a block of code to a serial or concurrent
queue.If you don’t want to go through the hassle of creating an NSOperation subclass for a
trivial task, then Grand Central Dispatch is a great alternative. Another benefit of Grand
Central Dispatch is that you can keep related code together. GCD is a library that provides a
low-level API to run tasks concurrently while managing threads behind the scenes.
Terminology.Dispatch Queues, A dispatch queue is responsible for executing a task in the
first-in, first-out order.
Serial Dispatch Queue A serial dispatch queue runs tasks one at a time.
Concurrent Dispatch Queue A concurrent dispatch queue runs as many tasks as it can
without waiting for the started tasks to finish.
Main Dispatch Queue A globally available serial queue that executes tasks on the
application’s main thread.
Main Queue: When the app is launched the system automatically creates a special queue
called as main queue. Work items on the main queue is executed serially on the applications
main thread.
NSOperationQueue: class regulates the execution of a set of NSOperation objects. An
operation queue is generally used to perform some asynchronous operations on a
background thread so as not to block the main thread.
NSOperation: API is great for encapsulating well-defined blocks of functionality. You
could, for example, use an NSOperation subclass to encapsulate the login sequence of an
application.Dependency management is the icing on the cake. An operation can have
dependencies to other operations and that is a powerful feature Grand Central Dispatch
lacks. If you need to perform several tasks in a specific order, then operations are a good
solution.You can go overboard with operations if you are creating dozens of operations in a
short timeframe. This can lead to performance problems due to the overhead inherent to the
NSOperation API.
• Be extended
• Conform to protocols
• Define initialisers
• Define Subscripts to provide access to their variables
Only class can do:
• Inheritance
• Type casting
• Define de initialisers
• Allow reference counting for multiple references.
1.One of the most important differences between structures and classes is that
structures are value types and are always copied when they are passed
around in your code, and classes are reference type and are passed by
reference.
2. Also, classes have Inheritance which allows one class to inherit the
characteristics of another.
3. Struct properties are stored on Stack and Class instances are stored on Heap
hence, sometimes the stack is drastically faster than a class.
4. Struct gets a default initialiser automatically whereas in Class, we have to
initialise.
5. Struct is thread safe or singleton at any point of time.
And also, To summarise the difference between structs and classes, it is necessary to
understand the difference between value and reference types.
1. When you make a copy of a value type, it copies all the data from the thing you
are copying into the new variable. They are 2 separate things and changing
one does not affect the other.
2. When you make a copy of a reference type, the new variable refers to the same
memory location as the thing you are copying. This means that changing
one will change the other since they both refer to the same memory location.
114. What are some ways to support newer API methods or classes while maintaining
backward compatibility?
1. Set the Base SDK to Current version of Mac (ex. 10.7)
2. Set the Deployment SDK to older version (ex.1.4)
For instance, if you want your view to have a red tintColor (a method introduced in iOS 7),
but your app still supports iOS 6, how could you make sure it won’t crash when running on
iOS 6?
Treat deprecated APIs warnings as errors to resolve.At runtime, check for OS
versions.Control the number of 3d party libraries.objC : Mark legacy code paths with
macros.
if #available(iOS 8, *, *) {
self.view.convertPoint(.Zero, toCoordinateSpace:anotherView)
} else {
self.view.convertPoint(CGPointZero, toView:anotherView)
}
Why is this important? In Objective-C, if you want a method to return more than one
value you have two options return a custom object with properties that store your return
values or stick those values in a dictionary. With Swift however, we can use tuples to return
more than one value. The values in a tuple can be off any type and don’t have to be the
same type as each other.Tuples are value types. When you initialise a variable tuple with
another one it will actually create a copy.
116. What is an “app ID”, “bundle ID” , App Bundle and Signing?
bundle ID: is the identifier of a single app. For example, if your organisations domain is
xxx.com and you create an app named Facebook, you could assign the string
com.xxx.facebook as our app’s bundle ID.
App ID: is a two-part string used to identify one or more apps from a single development
team. You need Apple Developer account for an App ID.
App Bundle: When you build your iOS app, Xcode packages it as a bundle. App bundle is
a directory in the file system that groups related resources together in one place. An iOS
app bundle contains the app executable file and supporting resource files such as app icons,
image files, and localised content.
Signing: our app allows iOS to identify who signed our app and to verify that our app
hasn’t been modified since you signed it. The Signing Identity consists of a public-private
key pair that Apple creates for us.
117. if let, if var, guard let, guard var and defer statements in swift
Optional Binding (if -let statements) :
Use optional binding to find out whether an optional contains a value, and if so, to make
that value available as a temporary constant or variable.
An optional binding for the if statement is as follows −
If let constantName = someOptional {
//statements using 'constantName'
} else {
// the value of someOptional is not set (or nil).
}
Notes:
• Remember that your application target is its own module and that internal access is
the default. Your classes, structs, enums, properties and methods are all accessible
within the application module by default unless you choose to restrict access.
• As with Swift 3 you can add final to any access level, except open, to prevent
subclassing or overriding of a class method or property.
119. networking, Get, Post, REST, HTTP, HTTPs, JSON What’s that?
networking: Every application these days uses networking to get data from APIs and other
external resources. Many apps are useless when not connected to the internet. Every iOS
developer should know what’s available to them to build the service/networking layer of
their application.
GET: method will be showing the information information to the users. The data passed
using the GET method would be visible to the user of the website in the browser
address bar, characters were restricted only to 256, will be visible to the user as it
sended appended to the URL,About the data type that can be send, with Get method
you can only use text as it sent as a string appended with the URL, About form
default, Get is the default method for any form, has limitation in the size of data
transmitted.
POST: method information will not be shown to the user.when we pass the information
using the POST method the data is not visible to the user directly, characters were
not restricted, will not be visible as it is sent encapsulated within the HTTP request
body.About the data type that can be send, with Post method you can use text or
binary as it sent as a string appended with the URL, if you need to use the post
method, you have to change the value of the attribute "method" to be Post, has no
limitation in the size of data transmitted
These days, NSURLSession and Codable are the two main technologies used for
networking on iOS but also knowing about open source solutions such as Alamofire is
beneficial.
HTTP stands for HyperText Transfer Protocol, transmits everything as plan text, it is fast
and cheap, HTTP is used most of the sites over the net, even this blogspot sites also use
HTTP, HTTP URLs starts with “http:// “ and use port 80 by default.HTTP is unsafe from
attacks like man-in-the-middle and eavesdropping 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.
REST: or Representational State Transfer, is a set of rules for designing consistent, easy-to-
use and maintainable web APIs.
JSON: stands for JavaScript Object Notation; it provides a straightforward, human-
readable and portable mechanism for transporting data between two systems. Apple
supplies the JSONSerialization class to help convert your objects in memory to JSON and
vice-versa.
mutableContainers :Specifies that arrays and dictionaries are created as variables objects,
not constants.
mutableLeaves: Specifies that leaf strings in the JSON object graph are created as
instances of variable String.
allowFragments: Specifies that the parser should allow top-level objects that are not
an instance of Array or Dictionary.
120.List out what are the control transfer statements used in Swift?
Control transfer statements used in Swift includes
• Continue
• Break
• Fall through
• Return
121.What is Property?
Swift 4 language provides properties for class, enumeration or structure to associate values.
Properties can be further classified into Stored properties and Computed properties.
Difference between Stored Properties and Computed Properties
Stored Property Computed Property
Store constant and variable values as Calculate a value rather than storing the
instance value
Provided by classes and structures Provided by classes, enumerations and
structures
Both Stored and Computed properties are associated with instances type. When the
properties are associated with its type values then it is defined as 'Type Properties'.
Stored and computed properties are usually associated with instances of a particular
type. However, properties can also be associated with the type itself. Such properties
are known as type properties. Property observers are also used
To observe the value of the stored properties
Stored Properties:
Swift 4 introduces Stored Property concept to store the instances of constants and
variables. Stored properties of constants are defined by the 'let' keyword and Stored
properties of variables are defined by the 'var' keyword.
During definition Stored property provides 'default value'
During Initialisation the user can initialise and modify the initial values
Note: Unlike stored properties, Swift requires you to use an explicit type with your
computed properties.
Lazy Stored Property:
Swift 4 provides a flexible property called 'Lazy Stored Property' where it won't
calculate the initial values when the variable is initialised for the first time. 'lazy'
modifier is used before the variable declaration to have it as a lazy stored
property.Lazy Properties are used to delay object creation.
When the property is dependent on other parts of a class, that are not known yet
Computed Properties.Rather then storing the values computed properties provide a
getter and an optional setter to retrieve and set other properties and values
indirectly.Lazy stored properties are used for a property whose initial values is not
calculated until the first time it is used. You can declare a lazy stored property by
writing the lazy modifier before its declaration. Lazy properties are useful when the
initial value for a property is reliant on outside factors whose values are unknown.
Bonus Tip : You do need to declare your lazy property using the var keyword, not the let
keyword, because constants must always have a value before initialization completes.
Benefit of lazy property increase performance in terms of speed.
Computed Properties as Property Observers:
In Swift 4 to observe and respond to property values Property Observers are used.
Each and every time when property values are set property observers are called.
Except lazy stored properties we can add property observers to 'inherited' property by
method 'overriding'.
Property Observers can be defined by either
Before Storing the value - will set
After Storing the new value - did set
When a property is set in an initialiser will set and did-set observers cannot be called.
In addition to stored properties, classes, structures, and enumerations can define computed
properties, which do not actually store a value. Instead, they provide a getter and an
optional setter to retrieve and set other properties and values indirectly.
122. What are the most important application delegate methods a developer should
handle ?
The operating system calls specific methods within the application delegate to facilitate
transitioning to and from various states. The seven most important application delegate
methods a developer should handle are:
application:willFinishLaunchingWithOptions:
Method called when the launch process is initiated. This is the first opportunity to execute
any code within the app.
application:didFinishLaunchingWithOptions:
Method called when the launch process is nearly complete. Since this method is called is
before any of the app’s windows are displayed, it is the last opportunity to prepare the
interface and make any final adjustments.
applicationDidBecomeActive:
Once the application has become active, the application delegate will receive a callback
notification message via the method applicationDidBecomeActive.
This method is also called each time the app returns to an active state from a previous
switch to inactive from a resulting phone call or SMS.
applicationWillResignActive:
There are several conditions that will spawn the applicationWillResignActive method. Each
time a temporary event, such as a phone call, happens this method gets called. It is also
important to note that “quitting” an iOS app does not terminate the processes, but rather
moves the app to the background.
applicationDidEnterBackground:
This method is called when an iOS app is running, but no longer in the foreground. In other
words, the user interface is not currently being displayed. According to Apple’s
UIApplicationDelegate Protocol Reference, the app has approximately five seconds to
perform tasks and return. If the method does not return within five seconds, the application
is terminated.
applicationWillEnterForeground:
This method is called as an app is preparing to move from the background to the
foreground. The app, however, is not moved into an active state without the
applicationDidBecomeActive method being called. This method gives a developer the
opportunity to re-establish the settings of the previous running state before the app becomes
active.
applicationWillTerminate:
This method notifies your application delegate when a termination event has been triggered.
Hitting the home button no longer quits the application. Force quitting the iOS app, or
shutting down the device triggers the applicationWillTerminate method. This is the
opportunity to save the application configuration, settings, and user preferences.
124. What is three triggers for a local notification and use of UserNotifications?
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.
We can add audio, video and images.
We can create custom interfaces for notifications.
We can manage notifications with interfaces in the notification centre.
New Notification extensions allow us to manage remote notification payloads before
they’re delivered.
class someClass{
func someMethod{
//some code
}
Optional binding is a term used when you assign temporary variables from optionals in the
first clause of an if or while block. Consider the code block below when the property
courses have yet not been initialised. Instead of returning a runtime error, the block will
gracefully continue execution.
if let courses = student.courses {
print("Yep, courses we have")
}
The code above will continue since we have not initialised the courses array yet. Simply
adding:
init() { courses = [Course]() }
Will then print out "Yep, courses we have.”
let closure = {
print("The result is \(calculator.sum)")
}
calculator.b = 20
135. What kind of benefits does Xcode server and Xcode Bot have for developers ?
Xcode server will automatically check out our project, build the app, run tests, and archive
the app for distribution.
Xcode Server uses bots to automatically build your projects. A bot represents a single
remote repository, project, and scheme. We can also control the build configuration the bot
uses and choose which devices and simulators the bot will use.
enum inherit from another enum. So inheritance one of the fundamental object-
oriented concepts cannot be applied to value types. On the other hand, value types can
inherit from protocols, even multiple protocols. Thus, with POP, value types have
become first class citizens in Swift.
Swift does not allow multiple inheritance for classes. However, Swift types can adopt
multiple protocols. Sometimes you may find this feature useful. You’ll also see how
the Swift team was able to use protocol extensions to improve the Swift standard
library itself, and how it impacts the code you write.
Swift supports multiple paradigms: Object-Oriented Programming, Protocol Oriented
Programming and Functional Programming.
The following diagram shows the class hierarchy for our Object-Oriented design:
This diagram shows that we have one superclass named Animal and two subclasses named
Alligator and Lion. We may think that, with the three categories, we would need to create a
larger class hierarchy where the middle layer would contain the classes for the Land, Air
and Sea animals however that is not possible with our requirements. The reason this is not
possible is because animal types can be members of multiple categories and with a class
hierarchy each class can have only one super class. This means that our Animal super class
will need to contain the code required for each of the three categories. Let's take a look at
the code for the Animal super class.
As we can see in these classes we override the functionality needed for each animal. The
Lion class contains the functionality for a land animal and the Alligator class contains the
functionality for both a land and sea animal. Since both class have the same Animal
superclass we can use polymorphism to access them through the interface provided by the
Animal superclass. Let's see how we would do this.
How we designed the animal types here would definitely work but there are several
drawbacks to this design. The first drawback is the large monolithic Animal superclass.
For those that are familiar with designed characters for video games you probably realise
how much functionality is actually missing form the Animal superclass and it’s subclasses.
This is on purpose so we can focus on the design and not all of the functionality. For those
who are not familiar with designed characters for video games, trust me when I say that this
class will get much bigger when we add all of the functionality needed.
Another drawback is not being able to define constants in the superclass that the subclasses
can set. We could define an initiator in the superclass that would set all of the constants
however the initiator would become pretty complex and that is something we would like to
avoid. The builder pattern could help us with the initiation but as we are about to see, a
protocol-oriented design would be even better.
One final drawback that I am going to point out is the use of flags (landAnimal, seaAnimal
and airAnimal properties) to define the type of animal. If we accidentally set these flags
wrong then the animal will not behave correctly. As an example, if we set the seaAnimal
flag rather than the landAnimal flag in the Lion class than the lion would not be able to
move or attack on land. Trust me it is very easy even for the most experience developer to
set flags like these wrong.
Now lets look at how we would define this same functionality in a Protocol-Oriented way.
Protocol-Oriented Design
Just like with the Object-Oriented design, we will want to start off with a type diagram that
shows the types needed to create and the relationships between them. The following
diagram shows our Protocol-Oriented design.
As we can see our POP design is different from our OOP design. In this design we use
three techniques that make POP significantly different from OOP. These techniques are
protocol inheritance, protocol composition and protocol extensions.
Protocol inheritance is where one protocol can inherit the requirements from one or more
other protocols. In our example the LandAnimal, SeaAnimal and AirAnimal protocols will
inherit the requirements of the Animal protocol.Protocol composition allows types to
conform to more than one protocol. This is one of the many advantages that POP has off
OOP. With OOP a class can have only one superclass which can lead to very monolithic
superclasses as we just saw. With POP we are encouraged to create multiple smaller
protocols with very specific requirements.Protocol extensions are arguably one of the most
important parts of the protocol-oriented programming paradigm. They allow us to add
functionality to all types that conform to a given protocol. Without protocol extensions if
we had common functionality that was needed for all types, that conformed to a particular
protocol, then we would have had to add that functionality to each type. This would lead to
large amounts of duplicate code and that would not be ideal to say the least.
Let's look at how this design works. We will start off by defining our Animal
protocol.Notice that we specify that the Lion type conforms to the LandAnimal protocol
while the Alligator type conforms to both the LandAnimal and SeaAnimal protocols.Having
a single type that conforms to multiple protocols is called protocol composition and is what
allows us to use smaller protocols rather than one giant monolithic superclass as in the OOP
example.
Both the Lion and Alligator types originate from the Animal protocol therefore we can still
use polymorphism as we did in the OOP example where we use the Animal type to store
instances of the Lion and Alligator types. Lets see how this works:
seeing some of the advantages that protocol-oriented programming has over object-oriented
programming, we may think that protocol-oriented programming is clearly superior to
object-oriented programming. Object-oriented programming and protocol-oriented
programming have similar philosophies like creating custom types that model real-world
objects and polymorphism to use a single interface to interact with multiple types. The
difference is how these philosophies are implemented.
To me, the code base in a project that uses protocol-oriented programming is much safer
and easier to read and maintain as compared to a project that uses object-oriented
programming. This does not mean that I am going to stop using object-oriented
programming all together. I can still see plenty of need for class hierarchy and inheritance.
139.What iOS architectures do you know that scale and design patterns are commonly
used in iOS apps, which one better for iOS Development?
Typical commonly used patterns when building iOS applications are those that Apple
advocates in their Cocoa, Cocoa Touch, Objective-C, and Swift documentation. These are
the patterns that every iOS developer learns. Apple refers to them as “core competencies”
design patterns. They include MVC, Singleton, Delegate, and Observer.
When an interviewer asks this question (in one form or another), he is looking for
something besides MVC. Because MVC is the go-to design pattern, the expectation is that
every iOS developer knows it. What they want to hear from you, though, is what else we
commonly use out of the box.
Design patterns are reusable solutions to common problems in software design.
They’re templates designed to help you write code that’s easy to understand and reuse.
They also help you create loosely coupled code so that you can change or replace
components in your code without too much hassle.
The most common Cocoa design patterns:
Creational: Singleton.
Structural: MVC, Decorator, Adapter, Facade.
Behavioural: Observer, and, Memento
How to Use the Memento Pattern:
iOS uses the Memento pattern as part of State Restoration, but essentially it stores and
re-applies your application's state so the user is back where they left things.
Singleton design pattern:
The Singleton design pattern ensures a class only has one instance, and provides a
global point of access to it. The class keeps track of its sole instance and ensures
that no other instance can be created. Singleton classes are appropriate for
situations where it makes sense for a single object to provide access to a global
resource.Several Cocoa framework classes are singletons. They
include NSFileManager, NSWorkspace, NSApplication,UIKit,UIApplication. A
process is limited to one instance of these classes. When a client asks the class for an
instance, it gets a shared instance, which is lazily created upon the first
request.Singleton is a class that returns only one and the same instance no matter
how many times you request it.Singletons are sometimes considered to be an anti-
pattern.
There are multiple disadvantages to using singletons:
The main ones are global state, object life-cycle, and dependency injection. When
you have only one instance of something, it’s very tempting to reference and use it
everywhere directly instead of injecting it into your objects. That leads to
unnecessary coupling of concrete implementation in your code instead of working
with an interface abstraction.
Another malicious side effect of “convenient” singletons is the global state. Often
singletons enable global state sharing and play the role of a “public bag” that every
object uses to store state. That leads to unpredictable results and bugs or crashes
1. One of the main disadvantages of singletons is that they make unit testing very hard.
They introduce global state to the application. The problem is that you cannot completely
isolate classes dependent on singletons. When you are trying to test such a class, you
inevitably test the Singleton as well. When unit testing, you want the class to be as loosely
coupled with other classes as possible and all the dependencies of the class should be
ideally provided externally (either by constructor or setters), so they can be easily mocked.
Unfortunately, that is not possible with singletons as they introduce tight coupling and the
class retrieves the instance on its own. But it gets even worse. The global state of stateful
singletons is preserved between test cases.
2. It is static so memory will not be freeze until app will killed. It has it's own creation time
and its own lifecycle.
serialQueue.sync{
result = dict[key]
}
Module - View - Controller, widely-known as MVC, is one of the first pattern approaches
of the Object - Oriented Programming. The View part is responsible for displaying
everything for system’s user (interfaces of mobile or web app, etc.). Model is generally
responsible for the databases, business entities and rest of data. In its turn, Controller
regulates the Model’s work, data provided to the database, display from the mentioned
database to the View part and vice versa.
The issue Apple’s system has lies in the tight connection between View and Controller
parts, tight almost to the point of having united View & Controller, and leaving Model part
separated. Consequently, it results in poor testing process only Model could be examined,
V&C (due to the tight connection they have) can not be tested at all.The robust connection
between Controller and View segments proved to be truly “unhealthy” when it comes to
software, so a new pattern saw the world soon.
Models: represent application data, any data objects, NSManagedObject subclasses and
similar are models
views: draw things on the screen, UIView subclasses (Cocoa Touch or custom) are views
controllers: manage data flow between model and view, UIViewControllers and their
subclasses are controllers
Massive View Controller is the state of a codebase where a lot of logic and responsibility
was showed into View Controllers that doesn’t belong there. That practice makes your code
rigid, bloated, and hard to change. There are other design patterns that can help you remedy
this, such as MVVM, MVP, and Coordinator. And there are architectures such as VIPER
and RIBs that were made specifically for the purpose of scaling iOS code and avoiding
Massive View Controller problem.
MVP pattern:
The Model View Presenter pattern has few key points, forming a vast gulf between it and
MVC:
MVP Model
• View is more loosely coupled to the model. The Presenter is responsible for binding
the Model to the View.
• Easier to unit test because interaction with the view is through an interface.
• Usually View to Presenter = map one-to-one. Complex views may have multi
presenters.
In this arrangement Model’s functions stay the same.Presenter is responsible for the
business logic respectively. The V part is the one of particular interest as it is divided into
two parts View and View Controller which are in authority for interaction. When there is a
MVVM vs MVC question, the system of this type solves the problem of a “heavy
addiction” View and Controller modes used to have in MVC pattern.
The testing obstacle is also solved in this case, as Model, View with user interaction, and
Presenter parts - all of these could be tested.The yet existing inconvenience is in Presenter’s
part yet way too massive, yet takes into the account all of the existing business logics.
Which is why the next act came into play, named…
MVVM pattern:
View: is again everything that user is capable of seeing - the layout, the structure and the
appearance of everything on the screen. Basically, within the application it would be app’s
page. View gets and sends updates to ViewModel only, excluding all the communication
between this part and Model itself.
ViewModel: is supposed to be an “interconnecting chain” between the View and Model
system components, and it’s main function is to handle the View’s logic. Typically, the view
model interacts with the model by invoking methods in the model classes. The view model
then provides data from the model in a form that the view can easily use, as Microsoft
states.
The main difference between MVC and MVVM is that MVVM’s distribution pattern is
better than in the previously-listed MVC, but when compared to MVP it is also massively
overloaded. Testing is a matter of particular importance here, as while plainly writing the
code you can not guarantee that the whole project will function properly tests, on the bright
note, help to ensure it will.
The next architectural patterns’ evolution has been recently released and is now the freshest
software architectural approach.
iOS VIPER architecture:
Clean Architecture splits the application’s logical structure into several responsibility levels.
In it’s turn, this “separation” resolves the tight dependency issues and increases the testing
availability of all levels.
As a common rule for all the patterns’ names, it is a backronym as well, for View,
Interactor, Presenter, Entity and Routing. Each of the VIPER’s parts is responsible for a
certain element, particularly:
View: is responsible for mirroring the actions user makes with an interface
Presenter: responsibilities within the VIPER pattern are quite limited - it receives the
updates from Entity, but doesn’t send any data to it;
Interactor: is the system’s part that actually corresponds with Entities. This scheme works
in the following direction: Presenter informs Interactor about the changes in the View
model, then Interactor contacts the Entity part, and, with the data received from Entity
Interactor gets back to Presenter, which commands View to mirror it for a user. All the data
models, all the entities and all the websites are connected to the Interactor part.
Entity: consists out of objects that are controlled by Interactor (titles, content. etc.)It never
interacts with Presenter directly, only via I-part.
Routing: (or Wireframe as it is sometimes called) is responsible for navigation between all
of the screens, and, essentially, for routing. Wireframe controls the objects of UIWindow,
UINavigationController and so on. Particularly within iOS architectural system it is all built
upon a framework called UIkit, which includes all the components of Apple MVC, but
without a tight connection that used to drive coders mad before.
VIPER module is as well beneficial once it comes to unit tests, as the great pattern’s
distribution lets you test all the functional available. In many ways this was the main
difficulty developers faced with previous MVC, MVP and MVVM software patterns.
All of these 4 software design patterns are often called one of the best architecture Patterns
for iOS development, even though all of them are less than ideal and definitely not
universally used for each and every project you get to develop. On the gloomy side, here is
a short list of issues each pattern has:
• MVC, MVP, MVVM - all of them have this “tight connection” issue, which makes
introducing updates to development, and testing them afterwards quite a harsh task
to accomplish.
• VIPER vs MVVM, MVC or MVP, is thought to be a winning case; although despite
its high flexibility and great testability also has many nuances that are hard to
generate.
Function builders unofficially arrived in Swift 5.1, but in the run up to Swift 5.4 they
formally went through the Swift Evolution proposal process as SE-0289 in order to be
discussed and refined. As part of that process they were renamed to result builders to better
reflect their actual purpose, and even acquired some new functionality.
First up, the most important part: result builders allow us to create a new value step by step
by passing in a sequence of our choosing. They power large parts of SwiftUI’s view
creation system, so that when we have a VStack with a variety of views inside, Swift
silently groups them together into an internal TupleView type so that they can be stored as a
single child of the VStack – it turns a sequence of views into a single view.
Result builders deserve their own detailed article, but I at least want to give you some small
code examples so you can see them in action.
Local functions now support overloading
SR-10069 requested the ability to overload functions in local contexts, which in practice
means nested functions can now be overloaded so that Swift chooses which one to run
based on the types that are used.
Property wrappers are now supported for local variables
Property wrappers were first introduced in Swift 5.1 as a way of attaching extra
functionality to properties in an easy, reusable way, but in Swift 5.4 their behavior got
extended to support using them as local variables in functions.
Packages can now declare executable targets
SE-0294 adds a new target option for apps using Swift Package manager, allowing us to
explicitly declare an executable target.
This is particularly important for folks who want to use SE-0281 (using @main to mark
your program’s entry point), because it didn’t play nicely with Swift Package Manager – it
would always look for a main.swift file.
With this change, we can now remove main.swift and use @main instead. Note: You must
specify // swift-tools-version:5.4 in your Package.swift file in order to get this new
functionality.
Matchers, supports
Expecta Good Both Good
async
OCHamcre
Good Simulator Good Matchers
st
• setUp() — This method is called before the invocation of each test method in
the given class.
• tearDown() — This method is called after the invocation of each test method
in given class.
You can customise setUp()and teardown() in 5 different ways,
1. Override setUp() class method to setup initial state for all test methods.
2. Override setUp() instance method to reset initial state before each test method is
executed.
3. You can have self-contained blocks of teardown code with the addTearDownBlock(_:)
method during a test method’s execution.
4. Override tearDown() instance method to clean after each test method executes.
5. Override tearDown() class method to clean after all test methods execute.
Convenience initialisers are used when you have some class with a lot of properties that
makes it kind of "Painful" to always initialise wit with all that variables, so what you do
with convenience initialiser is that you just pass some of the variables to initialise the
object, and assign the rest with a default value.Here is an example where you can see that
instead of initialising my object with all those variables Im just giving it a title.
struct Scene {
var minutes = 0
}
class Movie {
var title: String
var author: String
var date: Int
var scenes: [Scene]
convenience init(title:String) {
self.init(title:title, author: "Unknown", date:2016)
}
• scope, which determines where a name can be accessed - global and local
• storage duration, which determines when a variable is created and destroyed - static
and auto
Local: The variables which are declared inside the function, compound statement (or block)
are called Local variables.
Global: The variables declared outside any function are called global variables. They are
not limited to any function. Any function can access and modify global variables. Global
variables are automatically initialised to 0 at the time of declaration.
Static: A Static variable is able to retain its value between different function calls. The static
variable is only initialised once, if it is not initialised, then it is automatically initialised to
0. Here is how to declare a static variable, Static variables have a lifetime that lasts until the
end of the program. If they are local variables, then their value persists when execution
leaves their scope.
Auto: Automatic variables are local variables whose lifetime ends when execution leaves
their scope, and are recreated when the scope is reentered.
for i in 0..<len
{
let start = value.index(value.startIndex, offsetBy: i)
let end = value.index(value.endIndex, offsetBy: (i * -1) - 1)
if value[start] != value[end] {
return false
}
}
return true
}
print(isPalindrome("sass"))
● This property specifies the service level applied to operation objects added to the
queue ● If the operation object has an explicit service level set, that value is used instead.
The default value of this property depends on how you created the queue. For queues you
create yourself, the default value is NSOperationQualityOfServiceBackground. For the
queue returned by the main method, the default value is
NSOperationQualityOfServiceUserInteractive and cannot be changed.
https://www.allaboutswift.com/dev/2016/5/21/gcd-with-qos-in-swift
Types of QualityOfService ● User Interactive All UI related tasks need to be assigned that
QoS class. It basically tells iOS to run them on the main thread.
● User Initiated This is the class to choose if a task is triggered by the user but doesn't have
to be run necessarily on the main thread.
● Default This class is only listed for informational purposes only. The system defaults to
this class when not enough information is available to determine QoS.
● Utility This class needs to be chosen for tasks that have a dependency on other system
resources like file I/O or network I/O. Those tasks need to wait for a certain amount of time
before they are able to complete. They are always in one way or another initiated by the
user who waits for their completion.
● Background This class is supposed to be used for maintenance tasks - Tasks that don't
depend on their fast execution and that are oblivious to the user.
● Grand Central dispatch (Multi threading concept) GCD is a library that provides a low-
level and object-based API to run tasks concurrently while managing threads behind the
scenes. Terminology
● Dispatch Queues:- A dispatch queue is responsible for executing a task in the first-in,
first-out order
● Serial Dispatch Queue :- A serial dispatch queue runs tasks one at a time.
● Concurrent Dispatch Queue:- A concurrent dispatch queue runs as many tasks as it can
without waiting for the started tasks to finish.
● Main Dispatch Queue:- A globally available serial queue that executes tasks on the
application’s main thread.
}
print(polyname)
}
poly()
159.What is the difference between the Float, Double, and CGFloat data types?
Suggested approach: It’s a question of how many bits are used to store data: Float is always
32-bit, Double is always 64-bit, and CGFloat is either 32-bit or 64-bit depending on the
device it runs on, but realistically it’s just 64-bit all the time.
For bonus points, talk about how Swift 5.5 and onwards allows us to use CGFloat and
Double interchangeably.
160.Types of ranges?
There are multiple types of ranges in Swift you can use. The easiest way of working with
them is by making use of the range operator. Let’s go over the different types available in
Swift.
for all fonts in all apps, and it's surprisingly easy to use from both a developer and user
perspective. SwiftUI even defaults to using it across the board!
A. Development
--It’s use to test app internally
B.Production
--It’s use to upload app on app store
Profiles
There are two types of Profile
1.Development
2.Distribution
164.I have written for loop from 1 to 10. But when i=7 then then it comes out from
loop. I have not written any specific keyword nor exception generated. How it is
possible?
for(int i=0, i<10:i++)
{
if(i==6)
{
i=10;
}
}
Here I am trying to iterate from 0 to 9. This loop is iterating till Condition i<10 matches.
Now in iterating, when loop comes i=6 I will make i=10.
So in next iteration, i<10 condition is mismatched. So it comes out from loop.
There is no any keyword used or any exception generated.
• FCM is sent as JSON payloads and APNS sends either string or dictionary.
• FCM has a payload of 2KB while APNS has a payload of 4KB.
• VOIP notification - 5KB
• APNS saves 1 notification per App while FCM saves 100 notifications per device.
• FCM supports multiple platforms while APNS requires their proprietary platform.
• Acknowledgment can be sent in FCM if using XMPP, but it's not possible on APNS.
Advantage of FCM:
• Even if the user disallows notification, you can notify your app if the app is running
in the foreground (using shouldEstablishDirectChannel).
• Don't need to create dashboard to send notification on the device.
• Notification analytics on FCM Dashboard.
• Easy to create notification payload structure.
• App Server side handling is easy, Only one key is required for multiple apps and
platform (iOS, Android, Web)
i.e If input A = 23,B = 1472367 then Output : 3 . Because '23' is 3rd index in ‘1472367'.
let string = "iOSiQA is Very Helpful WebSite to Prepare for iOS Interview."
var output = ""
or
We can make protocol extension and provide default body to protocol method. So any class
or struct confirms that protocol doesn't require implementing that method.
protocol VoiceAssistant {
var s : String // Not allowed
var name: String {get} // Allowed
var voice: String {get set} // Allowed
"The Apple Push Notification service includes a feedback service to give you information
about failed remote notifications. When a remote notification cannot be delivered because
the intended app does not exist on the device, the feedback service adds that device’s token
to its list. Remote notifications that expire before being delivered are not considered a failed
delivery and don’t impact the feedback service. By using this information to stop sending
remote notifications that will fail to be delivered, you reduce unnecessary message
overhead and improve overall system performance.”
pem : this is a container format that may include just the public certificate (such as with
Apache installs, and CA certificate files /etc/ssl/certs), or may include an entire certificate
chain including public key, private key, and root certificates.
cdcd Desktop openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts
Types of Join :
1. Inner Join : If we use inner join between two table, then only data exists in both table, are
returned.
2. Outer Join :
Left Outer Join : It returns all data from left table(table1) and only matching data from
both table.
Right Outer Join : It returns all data from right table(table2) and only matching data from
both table.
3. Cross Join : It is like cartesian join. It returns all records from both table and it returns
table1.count * table2.count records in returns. Suppose table1 has 4 records and table2 has
3 records and returns 4*3 records.
4. Self Join : If some column's reference has in same table then self join is used. It is same
like inner join but here both left and right table are same. Its like if you table and Columns
are such as MainID, Name, ParentID then you can make query like
Select * from table t1 join table t2 on t1.MainID = t2.ParentID
If we have sqlite database which table structure can be changed after release. Then we need
to maintain database version. We can update database version by excecuting query like
PRAGMA user_version = version_num; (For swift : PRAGMA table_info(tblTest))
In second release If we need to add columns, then we can check database version, If
database version is old version then we can execute following query :
177.If there are two views up and bottom, up-view is 60% of superview and 40% of
superview respectively, then what to do with constraint?
Now,
We select height constraint of orange view equal to main view's height. And set multiplier
0.6. It shows ratio of orange view's height to main view's height. We have set 0.6 = 60/100 .
So orange view's height become 60% of main view's height.
Same we have done with green view and set multiplier 0.4 = 40/100 means 40%.
In above example, we set both label leading, trailing, top and bottom but not set width
constraint. So here conflicts will occur. You can see red line between two label showing
conflict.
Solution : If we have label's content hugging priority higher than there will be no conflicts
as hight priority label will not grow its size more than its content size. See below image :
Blue label has more content hugging priority (251) than green label(250). Blue label's width
will be set fixed as its content size.
Setting a higher value means that we don’t want the view to shrink smaller than the intrinsic
content size. It's simple : Higher the priority means larger the resistance to get shrunk.
Example . One button having large name and auto layout is set on button as its width is
become 40. So, button's content is not readable. See image :
Button horizontal compression resistance is 750 and width constraint priority is 1000.
For Solution, let's change horizontal compression resistance to 1000 and width constraint
priority less than 1000 i.e 999 . Now see effect on below image :
Button horizontal compression resistance is 1000 and width constraint priority is 999.
Notifies the view controller that its view is about to be added to a view hierarchy :
Notifies the view controller that its view was added to a view hierarchy :
Distribution Types :
Fill(Default) : When you place your controls inside a UIStackView with Fill set as the
distribution, it will keep all but one of the controls at their natural size and stretch one of
them to fill the space. It determines which control to stretch by noting which one has the
lowest Content Hugging Priority (CHP).
Fill Equally : With this type, each control in a UIStackView will be of equal size. All of the
space between the controls will be used up, if possible. I added a spacing of eight between
the UITextFields, so again you could see the size of each one. With this type, the CHP does
not matter, because each control is the same size.
Fill Proportionally : The UIStackView will ensure the controls maintain the same
proportion relative to one another as your layout grows and shrinks. Unlike the previous
two settings, the Fill Proportionally distribution needs the controls to have an intrinsic
content size. The Fill and Fill Equally distribution tell their child controls how big they
should be, but this one is the other way around (as long as there is enough space for all of
your controls to be their natural size). The proportions for the images and labels are
maintained for the different layout sizes.
Equal Spacing : This distribution type will maintain an equal spacing between each of the
controls and will not resize the controls themselves.
Equal Centring : It will equally space the centres of the controls. Space between every
control is equal.
184.How much experience do you have using iBeacons? Can you give examples?
Suggested approach: iBeacons were introduced way back in iOS 7, and have found mixed
use – unless you’re applying for an iBeacon development job this is one you can probably
skip with “I haven’t used them much, but I’m keen to learn!”
Of course, if you do have experience then this is your time to shine: talk about major and
minor identifiers, talk about positioning beacons overhead to avoid interference from
people and devices, talk about ranging, and more.
186.Can you talk me through some interesting code you wrote recently?
Suggested approach: Hopefully you can go straight to GitHub and pick an interesting
project. If not, why not? Your projects don't need to be amazing, clever, or even popular, but
if you literally have nothing to show you’re going to have a much harder job convincing
companies to hire you.
187.Do you have any favorite Swift newsletters or websites you read often?
Suggested approach: Most employers will say it's important to be able to demonstrate that
you’re committed to learning more about your craft. I subscribe to iOS Dev Weekly, Swift
Weekly Brief, and This Week in Swift – all are interesting. Obviously I would hope you
mention Hacking with Swift too, but I'm biased!
189.If you could have Apple add or improve one API, what would it be?
Suggested approach: This is a personal choice, and is asked to see how creative or
interesting your answer is. If it were me, I’d love to see either a handwriting detection API
so that we could add handwriting support everywhere, or a weather API so that apps could
integrate weather information in all sorts of places – imagine having a calendar app with
weather forecasts built right in!
190.What books would you recommend to someone who wants to learn Swift?
Suggested approach: Obviously I’d recommend the complete Hacking with Swift series, but
the point is that it gives you a chance to talk about how you learned Swift. You can always
list Apple’s official Swift guide if you’re desperate. Note: Saying "I didn't use any books, I
just worked hard" is a valid answer, but you should at least be aware that such an approach
doesn't work for many people.
192.Have you ever filed bugs with Apple? Can you walk me through some?
Suggested approach: This is about demonstrating you’re a good citizen of the iOS
community: you file bugs with Apple when you find them, and (just as important!) they are
useful bugs with details and ideally a test case. If you file these properly, walking through
shouldn’t be hard. Keep in mind that if you file bad bugs with Apple it suggests you'd be
pretty bad at filing internal bugs for your own company too.
Second, tvOS apps cannot explicitly use local storage. At product launch, the devices ship
with either 32 GB or 64 GB of hard drive space, but apps are not permitted to write directly
to the onboard storage.
tvOS app bundle cannot exceed 4 GB.
195.What steps do you take to identify and resolve battery life issues?
Suggested approach: This is something so many developers don’t ever think about, so use
this as your chance to shine: talk about optimizing drawing, batching network requests, and
minimizing work when the user isn’t interacting with the app.
Keep in mind that the battery settings app on iOS automatically shows which apps use the
most battery life for a user, so having poor battery performance is very visible.
198.How much experience do you have using Face ID or Touch ID? Can you give
examples?
Suggested approach: If you’re applying for a job at any company that has secure user data,
biometric authentication is almost certainly involved somewhere. Fortunately, it’s not hard
to learn!
For bonus points mention the need for a password backup in case Face ID/Touch ID fails,
but if you're generally stuck here a good approach might be just to say "I haven't used it
before, but I have used the keychain for secure storage."
199.How would you explain App Transport Security to a new iOS developer?
Suggested approach: This is your chance to demonstrate your security knowledge: why is
HTTPS so important, and in what specific cases might you need to opt out? It also an
opportunity to demonstrate your awareness of Apple's app review guidelines, which require
secure transmission of user data.
200.How would you calculate the secure hash value for some data?
Suggested approach: Secure hash values use something like SHA-3, which is not the kind
of code you'd want to write yourself. Instead, the best approach here is to mention
something like Apple's CryptoKit framework, which can do hashing and encryption
quickly, efficiently, and correctly.
202.Apart from the built-in ones, can you give an example of property wrappers?
Suggested approach: If it weren’t for the built-in restriction, this would be easy to answer
with @State, @EnvironmentObject, and more, but with that restriction in place you need to
be more creative – what real example can you think of? For example, a wrapper to make
sure numbers are never negative, or strings are never empty, or perhaps arrays that silently
stay sorted.
Suggested approach: I would suggest you start off nice and broad, and say that the
environment acts a bit like a singleton manager – you place objects in there and share them
in many places. But then you want to dive into the details a little more, perhaps saying that
actually you can subdivide the environment if you want, allowing some views to have
different environment objects.
I would recommend you try to mention how the environment differs from just injecting an
ObservableObject instance in an initializer.
If you want to talk about tags for NavigationLink views you can, but I would say the
important thing here is to think about why it's important – handling deep links from
Spotlight or widgets are both good places where you need to navigate programmatically.
TCP provides extensive error checking UDP has only the basic error checking
mechanisms. It is because it provides mechanism using checksums.
flow control and acknowledgement of
data.
TCP is comparatively slower than UDP. UDP is faster, simpler, and more efficient
than TCP.
TCP has a (20-60) bytes variable length UDP has an 8 bytes fixed-length header.
header.
TCP is used by HTTP, HTTPs, FTP, UDP is used by DNS, DHCP, TFTP,
SMTP and Telnet. SNMP, RIP, and VoIP.
Suppose there are two houses, H1 and H2 and a letter has to be sent from H1 to H2. But
there is a river in between those two houses. Now how can we send the letter?
Solution 1: Make a bridge over the river and then it can be delivered.
Solution 2: Get it delivered through a pigeon.
Consider the first solution as TCP. A connection has to made ( bridge ) to get the data
(letter) delivered.
The data is reliable because it will directly reach another end without loss in data or error.
And the second solution is UDP. No connection is required for sending the data.
The process is fast as compare to TCP, where we need to set up a connection(bridge). But
the data is not reliable: we don’t know whether the pigeon will go in the right direction, or it
will drop the letter on the way, or some issue is encountered in mid-travel. types
print( arr1[0])
Regular expressions are special string patterns that describe how to search through a string.
223.What is TVMLKit?
TVMLKit is the glue between TVML, JavaScript, and your native tvOS application.
225.Determine the value of X in the Swift code below. Explain your answer?
Consider the code:
class Cricket
{
var score = 100
}
var player1 = Cricket() var player2 = player1 player2.score = 200 print((player1.score),
(player2.score))
Ans:200,200(Classes are reference type)
var a1 = [1, 2, 3, 4, 5]
var a2 = a1
a2.append(6)
var x = a1.count
Determine the value of x.
Answer: (Structs are reference type)
In Swift, arrays are implemented as structs, making them value types rather than reference
types (i.e., classes). When a value type is assigned to a variable as an argument to a function
or method, a copy is created and assigned or passed. As a result, the value of x or the count
of array a1 remains equal to 5 (answer) while the count of array a2 is equal to 6, appending
the integer 6 onto a copy of the array a1. The arrays appear in the box below.
227.Find the bug in the Objective-C code below. Explain your answer?
Problem:
Consider:
@interface HelloWorldController : UIViewController
@end
@implementation HelloWorldController
- (void)viewDidLoad {
CGRect frame = CGRectMake(150, 150, 150, 50);
self.alert = [[UILabel alloc] initWithFrame:frame];
self.alert.text = @"Hello...";
[self.view addSubview:self.alert];
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
sleep(10);
self.alert.text = @"World";
}
);
}
@end
Answer:
All UI updates must be performed in the main thread. The global dispatch queue does not
guarantee that the alert text will be displayed on the UI. As a best practice, it is necessary to
specify any updates to the UI occur on the main thread, as in the fixed code below:
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
sleep(10);
dispatch_async(dispatch_get_main_queue(), ^{
self.alert.text = @"World";
});
});
print(arrayOfTuples) // prints [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
Can you rewrite this code in a more "swiftier" way?
Answer:
Yeap, the way to do it is:
let list = [Int](1...5)
let arrayOfTuples = Array(list.enumerated())
print(arrayOfTuples) // prints [(offset: 0, element: 1), (offset: 1, element: 2), (offset: 2,
element: 3), (offset: 3, element: 4), (offset: 4, element: 5)]
or with map:
let list = [Int](1...5)
let arrayOfDictionaries = list.enumerated().map { (a, b) in return [a : b] }
print(arrayOfDictionaries) // prints [[0: 1], [1: 2], [2: 3], [3: 4], [4: 5]]
229.What are the projects you were involved in so far? What technologies did you use
there?
just give some more details about some interesting projects, like what technologies, what
frameworks have you used, etc.
230.Are you involved in any open source projects? What is your role there?
that would be a big plus, even if you are just a contributor. If you are trying to get your first
job it's a good way to prove your skills. Even better if you are a maintainer of the popular
repository.
231.How big were the teams? Have you been a leader in any of those projects?
just to know if you used to work alone, in big teams, remotely or only with local people,
etc.
232.What are the sources of your knowledge? Do you read any blogs or listen to any
podcasts? Name a few.
if you do then that might mean programming is not just your job but also a hobby and it's
usually better to hire you instead of someone who doesn't do that
233.Have you worked with Scrum/Agile? What do you think about that? When in
your opinion it can be good and when rather harmful?
just a quick question to see if you understand that scrum has its place and doesn't have to be
used ALWAYS
235.Do you go to conferences and local meetups sometimes? Do you have any favorite
one?
nothing serious in my opinion, it doesn't mean that you are a bad developer because you do
not go there, you might be just an introvert. But it's sometimes good to see if you are a
person that might promote the company on conferences or even do a speech.
By using high order functions, write code snippet to get a sum of all integers from both
Arrays?
Ans: 35
Higher order functions are simply functions that can either accept functions or closures as
arguments or return a function/closure.
Higher Order Functions are very useful and powerful and help us to write more elegantly
and maintainable code. Those functions are Map, Filter, Reduce, Sort, CompactMap etc.
let result =
[listOne.compactMap({ $0}),listTwo.compactMap({ $0})].flatMap({ $0}).reduce(0) { $0 +
$1 }
First compact map removes nil element from the array. Then by using a flat map, we
combine these two arrays.
And finally, reduce function will help to get the sum of array elements.
238.For your photo-gallery iPad application, What would be your preference as senior
developer, Alamofire or URLSession?
With URLSession APIs availability, Now it becomes easier to build up network requests.
The developer can build own networking layer on top of URLSession.
Alamofire is popular Elegant HTTP Networking library in Swift. Alamofire saves you a ton
of time and simplifies the use. It is a well-tested library. Maintained by very clever people.
Cost of including it - very small.
For small projects and projects with less time-line Alamofire is a good choice.
But for long term product, we can build in the house layer with NSURLSession. To avoid
third-party dependency and upgrade overhead.
239.Almost all companies are taking the subject of data security and privacy severely.
So how to protect user's sensitive data in iOS applications.?
Apple provides great security mechanisms like Keychain, data encryption, or App Transport
Security(which forces developers to use SSL pinning).
Keychain is the password management system developed by Apple. Logins, keys, and
passwords should be stored in Keychain.
For network request, SSL pinning is used to ensure that an application communicates with
the right server. For this, we need to save the SSL certificate within the app bundle.
Others security mechanisms are like using encryption methods like AES-256 encryption
while saving sensitive data to persistent storage or passing data over the internet.
240.What will be output for below code snippet? Also, analyze the memory
performance for this code?
class Student {
let name: String
init(name: String) {
self.name = name
}
var scoreCard: ScoreCard?{
didSet{
print("\(name) got \(scoreCard!.marks) marks in this exam")
}
}
}
class Scorecard {
let marks: Float
init(marks: Float) {
self.marks = marks
}
var student: Student?{
didSet{
print("\(marks) for \(student!.name) in this exam")
}
}
}
var student: Student?
var score:Scorecard?
student = Student (name: "Albert Einstein")
score = Scorecard (marks: 80)
student!.scoreCard = score
score!.student = student
student = nil
score = nil
Albert Einstein got 80.0 marks in this exam 80.0 for Albert Einstein in this exam. Here we
have defines two classes, Student and ScoreCard. Each student owns one scoreCard also
Each scoreCard belongs to the specific student.
Finally, we have created a student with the name "Albert Einstein" and ScoreCard with 80
marks. We assigned scorecard to student and student to scorecard. Now both objects are
strongly referencing to each other. So they will never be removed from memory. This code
will cause a memory leak.
To fix this, we have to use weak reference for scoreCard property of student class.
class Student {
let name: String
init(name: String) {
self.name = name
}
weak var scoreCard: ScoreCard?{
didSet{
print("\(name) got \(scoreCard!.marks) marks in this exam")
}
}
}
241.What is the difference between the consumable and non-consumable type of in-
app purchase?
• Consumable: Customer needs to buy consumable in-app purchase items every time
for the following cases,
◦ If he deletes the old app and installs again.
◦ In case of a change in device. It’s used for,
◦ Game currency
◦ Game Hints
◦ Extra health
◦ Extra experience points
◦ A package of exports to a new file format etc.
• Non-consumable: This type is commonly used in-app purchase. It's like a one-time
purchase. Customer can use that feature with multiple devices using his Apple ID.
Even if you delete and re-install application you can still restore your purchase
features. It’s used for:
◦ Upgrade to pro edition
◦ Remove Ads
◦ Full game unlock
◦ Unlimited hints
◦ Extra characters
◦ Extra accessories
◦ Bonus game levels
◦ City guide maps
242.Swift is a static language and Objective-C dynamic language. What does it mean?
• Swift is static: The compiler must have all information about all classes and
functions at compile time. You can "extend" an existing class (with an extension),
but even then you must define completely at compile time what that extension
consists of.
• Objective-C is dynamic: Objective-C was extremely influenced by Smalltalk, which
had demonstrated the benefits of duck typing. This is also known as late binding,
runtime binding, or the late dispatch. It’s dynamic because the responder of a
message isn’t baked in at compile time, but is deferred until the actual point of
sending the message.
243.What is the output of the following Program? let numbers = [1, 2, 3, 4]?
let numberSum = numbers.reduce(0, { $0 + $1})
Ans:10
Ans:I am subclass
247.Is it possible to create multiple storyboards in single project. If yes how to switch
from one storyboard to another?
Yes, By using segue and Storyboard Reference we can switch from one storyboard to
another storyboard.
252.what OAuth?
•
A way to refer to ranges within a series, perhaps encapsulating a start property and a
length property, both of type Int.
• A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each
of type Double.
In all other cases, define a class, and create instances of that class to be managed and passed
by reference. In practice, this means that most custom data constructs should be classes, not
structures.
Here it is claiming that we should default to using classes and use structures only in specific
circumstances. Ultimately, you need to understand the real world implication of value types
vs. reference types and then you can make an informed decision about when to use structs
or classes. Also, keep in mind that these concepts are always evolving and The Swift
Programming Language documentation was written before the Protocol Oriented
Programming talk was given.
removing values or many other operations. You can chain multiple operators together to
perform complex processing.
Think of values flowing from the original publisher, through a series of operators. Like a
river, values come from the upstream publisher and flow to the downstream publisher.
let name=input.sorted()
let numbers = name
let result = numbers.chunked(into: 2)
print(result)
print(numberGroups)
264.How you will store user info (username, password or token) securely in iOS?
You should always use Keychain to store usernames and passwords, and since it’s stored
securely and only accessible to your app, there is no need to delete it when app quits.