IOS Development

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What is a dictionary? Is it similar to other structures in other programming languages?

A dictionary stores associations between keys belonging to the same type, and values also belonging to the same type, in a collection with no defined ordering. Each value is associated with a unique key, acting as an identifier for that value within the dictionary. It is similar to what is known in other languages as a HashMap, with some subtle differences.

What is a framework in iOS?

A framework is a "skeleton" that has been packed in a bundle, to be used and distributed within other applications. A framework can contain a wide variety of extra resources (images, strings that already have been localized, data files, UI objects, etc.). Unless a framework has been released to the public, it generally contains the .h files that you need to run it, as well. A framework is a "skeleton" that has been packed in a bundle, to be used and distributed within other applications. A framework can contain a wide variety of extra resources (images, strings that already have been localized, data files, UI objects, etc.). Unless a framework has been released to the public, it generally contains the .h files that you need to run it, as well.

What is a provisioning profile?

A provisioning profile is a collection of digital entities that uniquely ties developers and devices to an authorized iPhone development team and enables a device to be used for testing. A development provisioning profile must be installed on each device on which you wish to run your application code. If you want to discuss this further with a candidate, you can ask him or her about the signing process of an iOS application.

What do you know about singletons? Where would you use one, and where would you not?

A singleton is simply a class that only allows a single instance. You can't re-up instances of a singleton class. One reason that tends to come uprepeatedly on the Internet is that of a "logging" class. In this case, a singleton can be used instead of a single instance of a class, because a logging class usually must be used over and over again ad nauseam by every class in a project.

What are "strong" and "weak" references? Why are they important, and how can they be used to help control memory management and avoid memory leaks?

A strong reference is one that occurs by default anytime that a variable is being created. There is an important property with reciprocal strong references, and it is that when this happens, a retain cycle occurs. In this situation, ARC will never be able to destroy the objects. This is described as being a memory leak. These types of reciprocal and strong references should always be avoided. When this is not possible, using weak references can come to the rescue. If one of these references is declared as weak, the retain cycle will be broken, and, therefore, the memory leak will be avoided.

What six instruments are part of the standard iOS set?

Among them, a candidate should come up with the names of Leaks, Multicore, Time Profiler, Zombies, System Usage, UI Recorder, Activity Monitor, Allocations, Core Animation. To follow up, functionality and particularities of each tool are good topics to delve into.

What is Auto Layout?

Auto Layout is a means by which developers can create user interfaces, by defining relationships between elements. It provides a flexible and powerful system that describes how views and the UI controls relate to each other. By using Auto Layout, you can get an incredible degree of control over layout, with a wide range of customization, and yield the perfect interface.

What is ARC?

Automatic Reference Counting (ARC) is a compiler feature that provides automatic memory management for all your Objective-C objects. Instead of having to manually retain and release operations, ARC lets you focus on the part of the code that is more interesting, the object graphs, and the relationships between objects in your application. Discussing ARC can veer into more interesting directions. If the candidate displays a solid profile, you might want to discuss the differences between traditional garbage collection methods. In the case of ARC, there is no background process deallocating objects at runtime, as in other technologies.

How do you work with storyboards in a large team?

Bigger teams ask this question. They especially suffer from a poor team devel- opment support from Apple tools. Expected answer: The main problem when working with storyboards in a big team is dealing with .storyboard file merge conflicts. When two developers change the same storyboard in different branches, they most likely will have a merge conflict. The benefits a unified monolith storyboard gives are quickly outweighed by the struggle teams experience with those merge conflicts. There are two solutions: 1. Don't use storyboards and define your AutoLayout in code. 2. Split your monolithic storyboard into multiple storyboards, typically one per view controller. That way, storyboard changes will happen only when one view controller is modified, which likely will help you avoid most of the merge conflicts.

What are the advantages and disadvantages of creating AutoLayouts in code versus using storyboards?

Bigger teams sometimes ask this question because they experience particular challenges when it comes to working with UI using storyboards. There's no right or wrong answer here; every approach has its advantages and disadvan- tages. Expected answer: Working with AutoLayout in storyboards is considered to be more typical, and Apple pushes a lot of examples showing how to do that. The advantages are that it's visual, drag-and-drop/plug-and-play-able, and you can, in some scenarios, actually render your UI in Interface Builder without actually running the app and waiting for the entire build process to happen. 96 Neat. But the disadvantages are very apparent when you need to debug your constraints or work in a team of more than two people. It is difficult to tell what constraints need to be there and what constraints need to be removed at a glance. And quite often, teams working with one storyboard modify it in different git branches, causing merge conflicts. Also, the advantages of defining AutoLayout in code are that it's very explicit, clear, and merge- and conflict-free. Disadvantages, on the other hand, are that it's difficult to work with Apple's AutoLayout constraints API in code (it can be helped if you use a library like Masonry) and you have to compile your app to see the results of rendering.

What are closures/blocks and how are they used?

Blocks and closures are an integral part of Objective-C and Swift development. This question used to be an advanced one for Objective-C developers but nowa- days it is a standard for both Objective-C and Swift so it is going to be asked in 100% of interviews. Expected answer: Blocks in Objective-C and closures in Swift declare and capture a piece of executable code that will be launched at a later time. You can either define them in-line or give them dedicated type names to be referenced and used later. Blocks and closures are the first steps to multi-threading and asynchronicity in Swift and Objective-C since they are the building blocks that capture work that needs to be executed at later time (a.k.a. asynchronously). Blocks/closures are reference types and will retain/strongly reference every- 43 thing put in them unless otherwise specified. You can avoid strong reference cycle issues by using the __block and __weak keywords in Objective-C (or, betterstill,use@strongify/@weakify)and[weak self]/[unowned self] in Swift. Blocks and closures syntax is notoriously hard to remember so if you find yourself stuck, check out these two websites: http://****ingblocksyntax.com/ http://****ingclosuresyntax.com/ If those domain names are offensive to you, try these more friendly alternatives.

What is the difference between delegation and KVO?

Both are ways to create relationships between objects. Delegation is a one- to-one relationship in which one object implements a delegate protocol and another uses it and sends messages, assuming that those methods are implemented, because the receiver promises to comply to the protocol. KVO is a many-to-many relationship in which one object can broadcast a message, and one or multiple other objects can listen and react to it.

What is the difference between struct and class in Swift? When would you use one or the other?

Both structs and classes in Swift can have properties, methods, subscripts or initializers, be extended, and conform to protocols. Classes are reference types. They increase their reference count when passed to a function or assigned to a variable or constant. They also have some extra stuff like inheritance from a superclass (structs can't do that), type casting, and deinitializers (former dealloc). Structs are so-called value types. That means that when a struct is as- signed to a variable or a constant, or is passed to a function, its value is copied instead of increasing its reference count. The key thing about choosing between using a class or a struct is reference or value passing. If you need to store some primitives (i.e. Ints, Floats, Strings, etc.), use struct. However, if you need custom behavior where passing by reference is preferable (so that you refer to the same instance everywhere), use class.

What are the requisite considerations when writing a UITableViewController that shows images downloaded from a remote server?

By itself, programming this feature can be a coding task for a prospective candidate. However, if the question is asked orally, the candidate should answer by citing some general guidelines on how to deal with the aspect of storage and asynchronicity derived from this problem. Some of the points to cover are • Only download the image when the cell is scrolled into view, i.e., when cellForRowAtIndexPath is called. • Download the image asynchronously on a background thread, so as not to block the UI, so the user can keep scrolling. • When the image has downloaded for a cell, we must check if that cell is still in the view or whether it has been reused by another piece of data. If it's been reused, we should discard the image. Otherwise, we must switch back to the main thread, to change the image on the cell. Depending on the accuracy of the conversation, you might want to steer this discussion toward how images can be cached for a later offline user, usage of placeholders, etc.

What is a category/extension? When is it used?

Categories and extensions are super-useful when developing with Objective-C and Swift. Having a handle on the benefits and limitations of categories and extensions is an important skill so expect this question on pretty much every interview. Categories in Objective-C and Extensions in Swift are ways to extend existing functionality of a class or type. They allow you to add additional methods in Objective-C and Swift without subclassing. And in Swift to add computed properties, static properties, instance/type methods, initializers, subscripts, new nested types, and make existing type conform to a protocol without subclassing. In Swift, extensions are used to extend the functionality of existing types or to make a type conform to a protocol. The drawback of extensions and categories is that they are globally applied, unlike protocols. This means that after you define an extension/category for a class or type, it will be applied to all the instances of that type, even if they were created before the extension/category was defined.

Core Data

Core Data: This is Apple's persistency framework. It's based on an object graph that describes the objects that should be saved. Then, you can directly work with these objects, and the framework takes care of saving it to a database.

What design patterns are you aware of in iOS and use?

Every developer being interviewed should be aware of MVC. This is the paradigm that iOS is built on top of. The more seniority a developer has, the more frameworks he/she will be able to discuss. Here, you could include MVVM, which helps developers to prevent Massive View Controllers. Also, a developer could explain the differences and advantages and disadvantages of different frameworks.

How is memory management handled on iOS?

Every iOS developer who has been in the game for a while should be comfortable talking about this topic. A poor knowledge of memory management can lead to memory leaks, poor performance, and disappointed managers, investors, developers, and users. An answer could start by pointing out that Swift uses automatic reference counting (ARC), which is essentially the same as in Objective-C. By default, all the references are strong references. Strong reference cycles can therefore occur, and this makes it impossible for ARC to deallocate the memory. This can be solved by using weak references. This conversation can extend to talking about unowned references. Unowned references are used in values that are always expecting to be other than nil and must therefore be defined as non-optional. Also, another possible aspect of the conversation could be a discussion of closures.

What options do you have with animation on iOS?

Expected answer: There are three major things you can use on iOS to animate yourUI:UIKit,Core Animation,andUIKit Dynamics. • UIKit is the basic animation that is used the most often. It can be trig- gered by running the UIView.animateWithDuration() set of meth- ods. Things that are "animatable" this way are frame, bounds, center, transform, alpha, and backgroundColor. • Core Animationisusedformoreadvancedanimation,thingsthatUI- Kit isn't capable of doing. With Core Animation, you will manipulate 98 the view's layer directly and use classes like CABasicAnimation to set up more complex animations. • UIKit Dynamicsisusedtocreatedynamicinteractiveanimations.These animations are a more complex kind where the user can interact with your animation half-way through and potentially even revert it. With UIKit Dynamics you'll work with classes like UIDynamicItem. Note: there's also a very handy dynamics animation library by Facebook called Pop that can help with it.

What can you use to store 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 79 • NSUserDefaults/Keychain • File/Disk storage • Core Data, Realm • SQLite In-memory arrays, dictionaries, sets, and other data structures are perfectly fine for storing data. They are fast and simple to use. The main disadvantage though is that they can't be persisted without some work and can't be used to store large amounts of data. NSUserDefaults/Keychain are simple key-value stores. One is insecure and another one is secure respectively. Advantages are that they are easy to use, relatively fast, and are actually able to persist things to disk. Disadvantages are that they were not made as a replacement for databases and can't handle large amounts of data or extensive querying. File/Disk storage is actually a way of writing pieces of data (serialized or not) to/from a disk using NSFileManager. The great thing about it is that it can handle big files / large amounts of data but the disadvantage is that it was not made for querying. CoreData or Realm are frameworks thats simplify work with databases.They are great for large amounts of data and perfect for querying and filtering. Dis- advantages are the setup overhead and learning curve.

How do you track bugs? What are your tools of choice?

Here, the candidate will want to talk about the tools of choice she/he might already know. A few of them to cite (with no endorsement to any particular company implied) are Apteligent (formerly Crittercism), Crashlytics/ Fabric, HockeyApp, or the Apple platform itself (when distributed, you can see crashes in iTunes Connect).

SQLite database:

If the data to be stored is complex or requires a huge amount of structured data, using an SQLite database is generally the best option.

How do you develop applications for iPad and iPhone?

If you select Device family as universal, when creating a new project, you will receive options to prepare different XIB files or storyboards for iPhone and iPad. At a code level, you can either check for the device or use proper naming while allocating it. At runtime, you might want to load some resources, depending on whether the device is an iPhone or iPad. From a programmatic code perspective, you could proceed as follows (in Swift): switch UIDevice.currentDevice().userInterfaceIdiom { case .Phone: // It's an iPhone case .Pad: // It's an iPad case .Unspecified: // }

What are the differences between copy and retain?

In a general setting, retaining an object will increase its retain count by one. This will help keep the object in memory and prevent it from being blown away. What this means is that if you only hold a retained version of an object, you share that copy with whoever passed it to you. Copying an object, however you do it, should create another object with duplicate values. Think of this as a clone. You do not share the clone with 28 CHAPTER 2 QUESTIONS FOR PROSPECTIVE CANDIDATES WHO HAVE BEEN WORKING WITH IOS FOR SOME TIME whoever passed it to you. When dealing with NSStrings in particular, you may not be able to assume that whoever is giving you an NSString is truly giving you an NSString. Someone could be handing you a subclass (NSMutableString, in this case), which means that they could potentially modify the values under the covers. If your application depends on the value passed in, and someone changes it, you could run into trouble

What database options are there for iOS applications?

Interviewers ask this question to gauge your experience with database solutions on iOS. Expected Answer: The go-to database solution on iOS is Core Data. There is also an option to use SQLite directly but tools are not that advanced for that, so you'll have to come up with some customizations of your own. Another popular database framework is Realm. Each one of them has their own advantages and disadvantages. Core Data is an object graph and persistence framework that is the go-to solu- tion for local database storage on iOS. Advantages of that framework are that it is widely used and is supported by Apple. You can use it almost out of the box in your project, and it does a decent job of persisting data and making querying more or less straightforward. A disadvantage is that the Core Data API is not that easy to use in some scenar- ios and specifically in a multi-threading environment. Another big disadvan- tage of Core Data is that there's a learning curve to it since it is not a straight-forward addition on top of a relational database where each object represents a row in a table (like in ActiveRecord, for example), but rather an object graph storage. Realm is an alternative to the Core Data database solution. It was built from the ground up to be easier to use and faster than Core Data or SQL. Advantages of Realm are that it's fast, has reactive features, is easier to use, is secure, and has entire cloud platform for syncing and other more advanced features. A disadvantage is that it is still in development - although the Realm team made a lot of progress recently - and as of the time of this writing, it doesn't have all the features on par with Core Data's NSFetchedResultsController. There are also issues with the size of realm databases. Due to their playback feature, it has to store way more data to replay the events that happened as compared to Core Data or SQL, which stores only the latest snapshot without keeping a history of all the changes. Realm has a lot of potential to become the most popular solution for database storage on iOS in the long run, especially with all the backend/syncing func- tionality they are building into it. SQLite is a relational database that powers Core Data under the hood. It can be accessed directly on iOS and used without Core Data, but it will require implementing custom tooling for accessing, reading, and writing to it. The main advantages of using SQLite directly are that it is going to be fast, and if you have SQL skills you can leverage them. The main disadvantage though is that you'll have to do all the heavy lifting of setting things up and accessing and migrating the database yourself; there are no good tools out there to help with that.

What is KVO (Key-Value Observation)?

KVO is one of the core parts of Cocoa Touch and is used widely across the platform. Expected answer: KVO stands for Key-Value Observation and provides mechanics through which you can observe changes on properties in iOS. In contrast to Delegate KVO entails a one-to-many relationship. Multiple objects could subscribe to changes in a property of another object. As soon as that property changes, all objects subscribing to it will be notified. Under-the-hood implementation uses instance variables defined with properties to store the actual value of the property and setters/getters supplied by synthe- sization of those properties. Internally, when you assign a property it will call willChangeValueForKey: and didChangeValueForKey: to trigger the change broadcast to observers. Another way that KVO is used in iOS apps is public broadcasting of mes- sages through NSNotificationCenter. The underlying mechanics are the same as with property KVO but the broadcasting can be triggered via a post: method on NSNotificationCenter default center rather than a property change. Originally an Objective-C feature, this is also available in Swift to classes sub- classed from NSObject. KVO on its own is a fairly bulky technology but it opens up a lot of possibilities that you can build on. There are a lot of great FRP projects like ReactiveCocoa and RxSwift that were built using KVO mechanics.

Keychain

Keychain is the tool for storing data securely. This is where you'd store user passwords and tokens, not NSUserDefaults. Typically, working with Keychain directly is a bit gnarly and tedious due to its C-based API. I recommend using a library wrapper like KeychainAccess or samkeychain instead. Advantages: • key-value storage for primitive values • secure Disadvantages: • inconvenient API • errors out and fails quite often An interesting fact is that stuff saved in Keychain, unlike anything stored in NSUserDefaults, will persist and survive an app uninstall/reinstall. The rea- son being is that NSUserDefaults is the storage that is tightly coupled with your application and Keychain is a global secure system storage managed by Apple. That is both an advantage and disadvantage that allows us to do nice things like storing a flag on the first application launch in Keychain, indicat- ing that the app was installed for the first time. Next time, if the user uninstalls 155 and then reinstalls your app, you can check whether the flag is present or not and go with default onboarding flow for a new user, for example, and do some other custom onboarding for returning users.

What do you use to lay out your views cor- rectly on iOS?

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 and align views on the screen. When answering this question you should at least mention CGRect Frames and AutoLayout, but it would be great to mention other options such a ComponentKit and other Flexbox and React implementation on iOS. Expected answer: 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 is preferred by Apple. AutoLayout is a technology that helps you define re- lationships between views, called constraints, in a declarative way, letting the framework calculate precise frames and positions of UI elements instead. There are other options for laying out views, such as ComponentKit and Lay- outKit, that are more or less inspired by React. 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.

What is MVC, how is it implemented in iOS, and does it have any alternatives?

MVC is a well-known design pattern that defines how each component must be implemented, how components communicate between each other, and where each functionality must reside. By default, Apple provides an implementation of the MVC pattern: the UIViews are the views in which the UI lives; the UIViewControllers support the controller that listens to the events and can, therefore, update the view according to our needs; and the model is the data that the application uses and that can reside in any object we create to store useful information. There are many alternatives to MVC. A common one could be using MVVM with Reactive Cocoa. Other alternatives could include Viper and using functional reactive code.

What is NSCoding?

NSCoding is a widely used protocol for data serialization necessary for some of the data-storing operations using NSUserDefaults, NSFileManager, and Keychain. Interviewers will most likely ask this as part of a discussion about storage options on iOS, NSUserDefaults, Keychain, and so on. Expected Answer: NSCoding is a Cocoa protocol that allows objects that adopt it to be serialized for NSUserDefaults, NSFileManager, or Keychain storage. The way it works is you implement the init?(coder decoder: NSCoder) and encodeWithCoder methods in the objects that comply to that protocol. Those methods decode and encode the object respectively for persis- tence and retrieval. The gotcha with implementing NSCoding is that every property that you en- code and decode needs to comply to the NSCoding protocol as well. All the "primitive" values such as String, Number, and Int already do that and ev- ery custom object that you're trying to serialize as one of the properties needs to comply to that protocol as well.

NSUserDefaults

NSUserDefaults can store key primitive values like NSNumberand NSString or objects that comply to the NSCoding protocol. Also, it can store arrays or dictionaries that contain objects that comply to the NSCoding protocol. The objects can be retrieved easily by accessing them with the key they were stored with. Typically we think of NSUserDefaults as a solution to store user settings or preferences or tokens in (although tokens really should be stored in Keychain). But in reality, for some apps, it's a perfectly good option for storing the main application data that acts as a database. As you will see in the following ex- ample, it's a perfectly reasonable substitution for our in-memory solution from the previous section.

What is NSUserDefaults?

NSUserDefaults is a class that allows a developer to save settings, properties, and information that is related to the application or the user data. NSUserDefaults stores keys and their associated value. The following types can be stored with NSUserDefaults: • NSData • NSString • NSNumber • NSDate • NSArray • NSDictionary Possible follow-up questions here could be the following: What are the differences from other storing mechanisms in iOS? Is it possible to store an image with NSUserDefaults? The answer is yes. An image can be transformed into Base64 and stored as an NSString. Another question is whether this would be an efficient use of NSUserDefaults. In general, the candidate should be prompted to discuss the benefits and disadvantages of using NSUserDefaults as opposed to other storage types.

What is NSUserDefaults?

NSUserDefaults is one of the common tools used in virtually every appli- cation for lightweight storage. Every iOS developer should be familiar with it. Expected Answer: NSUserDefaults is a key-value storage that can persist serialized NSCoding compliant objects and primitives. Unlike Keychain, it is not secure and does not persist between app uninstalls. It's main purpose is to store small objects that are easily retrievable but also not important to lose. 81 A typical use case for it is some locally stored user preferences and/or flags. Do not use it as a database replacement because it was not built for extensive querying or for handling large amounts of data.

What is MVC?

Oh, good old MVC. This is a fundamental design pattern Apple keeps pushing onto iOS developers. Every single interviewer will ask a question about this. Expected answer: MVC stands for Model View Controller. It is a software design pattern Apple chose to be the main approach to iOS application devel- opment. Application data are captured and represented by Models. Views are responsible for drawing things on the screen. Controllers control the data flow between Model and View. Model and View never communicate with each other directly and instead rely on Controller to coordinate the communication. A typical representation of each MVC layer in an iOS application would be the following: • UIView subclasses (Cocoa Touch or custom) are the Views • UIViewControllers and their subclasses are the Controllers • and any data objects, NSManagedObject subclasses and similar are the Models. MVC is a great general purpose design pattern but using it solely limits your architecture and often leads to notorious "Massive View Controller". " Massive View Controller" is the state of a codebase where a lot of logic and responsi- bility has been shoved into View Controllers that doesn't belong in them. 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 and the general SRP principle. Even though Apple keeps telling us that MVC is everything, don't be fooled by it and stick to SOLID principles.

How do you optimize table views performance for smooth, fast scrolling?

One of the important questions that is sometimes asked on interviews along with UITableView questions is a question about table view scrolling perfor- mance. Expected answer: Scrolling performance is a big issue with UITableViews and quite often can be very hard to get right. The main difficulty is cell height calculation. When the user scrolls, every next cell needs to calculate its content and then height before it can be displayed. If you do manual Frame view lay- outs then it is more performant but the challenge is to get the height and size calculations just right. If you use AutoLayout then the challenge is to set all the constraints right. But even AutoLayout itself could take some time to compute cell heights, and your scrolling performance will suffer. Potential solutions for scrolling performance issues could be • calculate cell height yourself • keep a prototype cell that you fill with content and use to calculate cell height Alternatively, you could take a completely radical approach, which is to use dif- ferent technology like ComponentKit. ComponentKit is made specifically for list views with dynamic content size and is optimized to calculate cell heights in a background thread, which makes it super performant.

What is Optional in Swift and nil in Swift

Optional is defined with ? appended at the end of the variable type you declare. You can set a value to that variable right away or at a later time or not set one at all. When you use Optional variables you have to either explicitly unwrap them, using ! at the end of the variable to get the value stored in it or you could also-called Optional Binding to find out when the ran Optional contains a value. Optionals can be used with constants (lets) only if they were give a value right away (whether it's nil or an actual value). In general a constant has to be defined at the time of its declaration and therefore it has a value and is not an Optional. In Swift, unlike in Objective-C, sending messages to nil causes a runtime exception. There is, though, a way of sending a message to an Optional in Swift and if the value is a nil, it will just ignore the message and return nil instead of raising an exception. This is much like the old Objective-C behavior and allows you to do method chaining calls. If one of the Optional values in the call sequence is nil, the whole chain will return nil. Optionals make Swift lean more towards the functional side of programming languages partially mimicking the Maybe concept of Haskel and similar lan- guages. Ultimately, just like let, var, and nil, Optional is a helpful con- struct that forces you to be more mindful of how you handle the state of your applications. In general, you should use nil and consequently Optionals to represent an absence of value as little as possible. Every time you declare an Optional, ask yourself if you really, really need it.

How does AutoLayout work with multi-threading?

Pretty much every iOS application these days has some kind of multi-threading. Interviewers ask this question to gauge your general understanding of how to work with the main thread and background threads and with UI in particular. Expected answer: All UI changes have to be done on the main thread. Just like working with Frames, working with AutoLayout is UI work and it needs to be performed on the main UI thread. Every AutoLayout constraint's addition or removal or constant change needs to be done on the main thread. After you change constraints, call the setNeedsLayout method.

What is a protocol (both Obj-C and Swift)? When and how is it used?

Protocols (or, in other languages, Interfaces) are dec- larations of what a type that adopts them should implement. A protocol only has a description or signature of the methods, properties, operators, etc. that a type implements without the actual implementation. In both Swift and Objective-C protocols can inherit from one or more other protocols. In Swift, protocols can declare properties, instance methods, type methods, operators and subscripts. They can be adopted by classes, structs, and enums. By default, everything in Swift protocols is required. If you'd like to have optional methods and properties, you have to declare your Swift protocol as Objective-C compatible by prefixing it with @objc. If you prefix your protocol with @objc, it can only be adopted by classes. Swift also lets you provide a default implementation for your protocols with a protocol extension. Protocols are a great addition to any OO language because they allow you to clearly and explicitly declare interfaces of things in your code and be able to rely on them. It is a way to abstract internal implementation details out and care about types rather than about inheritance structures. Declaring clear protocols allows you to dynamically change objects that conform to the same protocol at runtime. It also lets you abstract things out and code against interfaces rather than specific classes or other types. It helps, for example, with the implementa- tion of core Cocoa Touch design patterns such as Delegation. Also, developing against protocols could help with test-driven development (TDD) because stubs and mocks in tests could adopt the necessary protocols and substitute or "fake" the real implementation.

What are Singletons? What are they used for?

Singleton is a common design pattern used in many OOP languages and Cocoa considers it one of the Cocoa Core Competencies. This question comes up from time to time on interviews to either gauge your experience with singletons or to find out if you have a background in something other than just iOS. Expected answer: 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 two main ones are global state/statefulness and object lifecycle and dependency injection. Singletons are often misused and can breed in global state, which makes debugging and working with your code difficult. It starts off very innocently when you think you'll have only one instance of a class and you make it globally available across your codebase. But at some point you need to either reset it, do something else with the data stored on it, or realize that sharing it across the whole app doesn't make sense anymore. This is when you get into trouble because your singleton is everywhere now and data stored in it is unreliable because you don't know who might've changed it and when. Using singletons makes it hard for you to inject dependencies because with a singleton there's only one instance of your singleton class. That prevents you from injecting it as a dependency for the purposes of testing and just general inversion of control architecture.

What is Keychain and when do you need it?

Storing data securely is important for every iOS app, big or small. This ques- tion is assessing your experience with iOS secure key-value storage. Expected Answer: Keychain is a secure alternative to NSUserDefaults. It is a key-value store that is encrypted by the system and persists between app reinstalls unlike other types of data such as NSUserDefaults, files on disk, and Core Data databases. The advantage of Keychain is that it is secure, but the disadvantage is that its API is difficult to use. The main use case for Keychain is to store small objects and primitives, such as tokens and passwords, securely. Use it instead of NSUserDefaults for that purpose, and just like with NSUserDefaults do not use it to store large amounts of data, such as databases, images, and videos.

How do you save data to a disk on iOS?

Storing files on a disk is a more or less common thing to do in iOS applications. Don't expect this question that often, but note that it could come up from time to time in the context of storage. 82 Expected Answer: File storage is used to persist large amounts of data on a disk such as images, videos, and other kinds of files. NSFileManager is the class you would use to manipulate you app's folder on a disk. It is capable of creating subdirectories and storing files. You can store or read any NSData ob- ject whether it's an image, video, or an object serialized through the NSCoding protocol.

What is a struct in iOS?

Structs are named types that allow for grouping items into one variable. A struct in Swift would look as follows: struct SomeStruct { var name: String var attribute: String } A good follow-up question for the candidate is to explain the difference between classes and structs, and where they can be more efficiently used. In Swift, structs are copied, and classes are referenced. Thus, they will be passed as values, not as references, in the case of large objects. Swift uses structs to improve performance, even with String and Array objects. Structs are preferable if • The purpose is to encapsulate a few data values. • The structure does not have to inherit values from other existing types

How is memory management handled in iOS?

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 unassign instances of classes (reference types) to constants, properties, and variables. It deallocates memory used by objects which reference count got down 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. One of the gotchas of ARC that you need to be aware of is Strong Reference Cycles. For a class instance to be fully deallocated under ARC, it needs to be free of all strong references to it. But there is a chance that you could structure your code in such a way that two instances strongly reference each other and therefore never let each other's reference count drop down to zero. There are two ways of resolving this in Swift: weak references and unowned references. Both of these approaches will assign an instance without keeping a strong ref- erence to it. Use the weak keyword for one and the unowned keyword for the other before a property or variable declaration. Weak reference is used when you know that a reference is allowed to become nil whereas unowned refer- ence is used when you are certain that the reference has a longer lifecycle and will never become nil. Since weak references can have a value or no value at all, they must be defined as optional variables. An unowned reference has to be defined as non-optional since it is assumed to always have a value. Another important gotcha is Strong Reference Cycle in Closures. When you use closures within a class instance they could potentially capture self. If self, in turn, retains that closure, you'd have a mutual strong reference cy- 38 cle between closure and class instance. This often occurs when you use lazy loaded properties for example. To avoid it, you'd use the same keywords weak and unowned. When you define your closure, you should attach to its defi- nition a so called capture list. A capture list defines how the closure would handle references captured in it. By default, if you don't use a capture list, everything will be strongly referenced. Capture lists are defined either on the same line where the closure open bracket is or on the next line after that. They are defined with a pair of square brackets and every element in them has a weak or unowned keyword prefix and is separated from other elements by a comma. The same thinking applies to a closure capture list as to variable references: define a capture variable as a weak Optional if it could become nil' and the closure won't be deallocated before then, and define a captured reference as unowned if it will never become nil before the closure is deallocated.

How do you make a pixel-perfect UI accord- ing to a designer's specs?

Teams that are very heavy on design and sleek UI typically ask this question. Expected answer: The short answer is you don't. The long answer is that it depends. It depends on how you define "pixel-perfect UI." Ideally, if your designer thought through all the edge cases of your UI laid out on various devices sizes and talked to you about cases where there's no content, and so on, then you could hypothetically build a "pixel-perfect UI." But, in reality, that's often not the case; you discover inconsistencies or edge cases in UI and UX as you build them. Designing UI/UX is not a finite thing - it's a constantly evolving process that is never done. Your best bet is to do your best today and have a short and quick feedback loop with your designer and stakeholders to adjust the UI/UX as you go. Red flag: Don't say that you "just use a Photoshop or Sketch file and eyeball it."

What is the difference between a frame and bounds

The frame of a UIView in iOS is an imaginary rectangle relative to the location of the superview in which it is contained. On the other hand, the bound is the relative rectangle to its own coordinate system. Both items are expressed as a location with x, y as the starting points and a size indicated by width and height.

When are let and var appropriate in Swift?

The let keyword defines a constant. let theAnswer = 42 theAnswer cannot be changed afterward. This is why anything optional or weak can't be written using let. The former has to change during runtime and must be written using var. var defines an ordinary variable. var president = "Lincoln"

What is let and var in Swift?

The let keyword is used to declare a constant variable and the var keyword is used to declare a variable. Variables created with these are either references/pointers or values. The difference between them is that when you create a constant with let, you have to give it a value upon declaration (or within the calling scope) and you can't reassign it. In contrast, when you declare a variable with var, it can either be assigned right away or at a later time or not at all (i.e. be nil).

What does iOS application lifecycle consist of?

The main point of entry into iOS apps is UIApplicationDelegate. UIApplicationDelegate is a protocol that your app has to implement to get notified about user events such as app launch, app goes into background or foreground, app is terminated, a push notification was opened, etc. Launch • application: didFinishLaunchingWithOptions: -> Bool is called next. This callback method is called when the application has finished launching and restored state and can do final initialization such as creating UI. • applicationWillEnterForeground: is called after application: didFinishLaunchingWithOptions: or if your app becomes active again after receiving a phone call or other system interruption. • applicationDidBecomeActive: is called after applicationWillEnterForeground: to finish up the transition to the foreground. Termination • applicationWillResignActive: is called when the app is about to become inactive (for example, when the phone receives a call or the user hits the Home button). • applicationDidEnterBackground: is called when your app enters a background state after becoming inactive. You have approximately five seconds to run any tasks you need to back things up in case the app gets terminated later or right after that. • applicationWillTerminate: is called when your app is about to be purged from memory. Call any final cleanups here. Both application: willFinishLaunchingWithOptions: and application: didFinishLaunchingWithOptions: can potentially be launched with options identifying that the app was called to handle a push no- tification or url or something else. You need to return true if your app can handle the given activity or url. Knowing your app's lifecycle is important to properly initialize and set up your app and objects. You don't have to run everything in application: didFinishLaunchingWithOptions, which often becomes a kitchen sink of setups and initializations of some sort.

What are different ways in which you can specify the layout of elements in a UIView?

There are a few different techniques to specify a layout in an iOS app. • We can use InterfaceBuilder to add an XIB file to our project. Later, this XIB file can be loaded from within our application code. InterfaceBuilder also allows us to create a storyboard. • You can write your own code to use NSLayoutConstraints, to have elements in a view arranged by Auto Layout. • You can create CGRects describing the exact coordinates for each element and pass them to UIView's- (id)initWithFrame:(CGRect)frame method.

What's your preference when writing UIs: XIB files, storyboards, or programmatic UIView?

There are arguments supporting each of the different models. It would be presumptuous to pretend to have a definitive answer. Instead, this question aims to discuss with a candidate his/her thinking and reasons for preferring one or another alternative (or which scenario they fit better). A possible answer could relate the advantages and disadvantages of each mechanism, for example: Advantages of XIB files: • You can quickly put together a UI. • Provides straightforward implementation for small apps with a minimal number of screens. • You can have separate XIBs for different localizations (i.e., languages or countries). • They are great at laying out elements and visually spotting misalignments. They make it easy to make slight adjustments to the layout. Disadvantages of XIB files: • It's difficult to merge conflicts when working in a team environment (hard to diff, merge, and read). • Highly dynamic views are impossible to describe as an XIB. • Performance wise, they are slower than creating views through code, because the XIB has to be read from the disk and analyzed/parsed. XIBs lack customizations that you can do in code, such as Quartz stuff (drop shadows, round corners). They are harder to debug (i.e., if you forget to make a connection in Interface Builder or make a wrong connection). Advantages of storyboards: • Storyboards are nice for apps with a small to medium number of screens and relatively straightforward requirements for navigation between views. • You can mock up the flow of an application without writing much, if any, code. Disadvantages of storyboards: • Storyboards are not compatible with pre-iOS 5, so they make supporting iOS 4.3 impossible. • It's hard to work in parallel in a team environment, because everyone's modifying the same file. • Along the same lines, merging conflicted storyboards in GIT will be a pain. • With storyboards, people have experienced bugs in Xcode (e.g., having to frequently flush the DerivedData folder because of inconsistencies). Advantages of views created programmatically: • It's easier to merge conflicts and diff lines of code than with an XIB file. • You can trace through code when debugging and not have to look at Interface Builder. • Performance wise, it offers faster view creation than XIBs. • Creating views through code gives you more control and free rein. Disadvantages with views created programmatically: • It's harder to visualize the UI and gain a mental picture of what it will look like, if all your UI creation doesn't happen in one place in your code. • You can't visually position elements, making it more time-consuming to lay out your views. • It will take newcomers to your project team longer to grasp the app flow and navigation

How can you keep different flavors for production and development releases?

There are different approaches that could be used here. An initial one could be to create different targets, each of them employing different Info. plist files. Each time a target is selected, a different Info.plist will be used, thereby being able to differentiate between different variables (for example, tokens, URLs, etc.). One could also think of using bundle identifiers. Defining different preprocessor macros will control the conditional compilation of various chunks of code. Alternatively, or in addition, you could put your build configuration settings (including the changing location of the Info.plist file) into *.xcconfig files and reference those in your project, info, and configurations areas. Then, you could build a different version of your app simply by changing your scheme. Putting build configuration settings into files is a huge win for configuration control too.

How do you test your code? How do you make your code testable

These are also important questions that can branch into many interesting tangents and will, we hope, let us know about the candidate's mindset and theoretical knowledge. A relevant discussion could be of the perks of having manual testing and automated testing. Each type of test has different pros and cons. Let's talk about automated testing. • Tests can run rather quickly, because there is no need for a human. • They can be cost-effective, if we make proper use of the tools for automation. They can be expensive in the short term but definitely lower costs in the long run. -Everyone can see results. Tests can be reproduced, recorded, and saved. -On the other hand, tools might have limitations, and we might be constrained to the development of our testing tool or API. Manual testing can also have its own virtues and vices. • In the short term, it lowers costs. • It is more likely to uncover real user issues. Because automatic tests are automated, they will not test special edge use cases or improvise and test something not provided in the script. • On the other hand, some tasks can be rather difficult to perform manually, at worst, repetitive, boring, and not at all stimulating. A candidate also could be prompted with the question, Which testing frameworks do you use? XCTest is tightly coupled with Xcode, and, therefore, most developers should have at least a minimum theoretical idea of the framework. Other testing frameworks include Appium and Calabash. To dive deeper, you could discuss the advantages and disadvantages of each framework. This could be convenient way to align the knowledge of the candidate with the knowledge of a company, although a candidate should never be hired based only on the knowledge of frameworks he/she possesses but on his/her general attitude and reasoning. The frameworks of today will be in the museums of tomorrow. Last, but not least, an interesting discussion on the topic is how to make code testable. Principles to create a testable code always make for interesting conversation, and among them, SOLID is a very good starting point.

Files

These can be directly saved in the application (for security reasons, an app can only access its own app container). If you want to dive deeper, a potential candidate could discuss reasons for choosing SQLite over Core Data, for example. One reason could be that SQLite can be shared among different applications in other platforms, whereas Core Data is a framework exclusively available for Apple.

User Defaults

These can be used to persist a small amount of data. Typical examples are part of the configuration required to run the application. User defaults can persist the primitive types in iOS (String, Data, Number, Date, Array, and Dictionary).

How do you typically do networking?

This conversation can be very interesting and reveal many insights into a developer's approaches. A developer should mention architectures he/ she has used and the patterns he/she relies on. These can include service layers, MVVM, UI data binding, dependency injection, or functional reactive programming. Which libraries does the developer use? Developers come from different backgrounds and might be using AFNetworking, ReactiveCocoa... How does he/she ensure that data can be saved from the network? What is the process from the time the user clicks a UI component until the data is stored locally on a device? What classes are involved in the selected architecture? How would the developer prepare the application for offline use, and does he/she approach caching? How would he/she define an ideal API for mobile. Is he/she aware of all the HTTP methods (PUT, POST, GET, DELETE) and when and how would he/she use them? There are no right/wrong answers to the preceding questions. Rather, they present a golden opportunity to discuss with an experienced potential colleague approaches that could also serve you, by comparing your own processes with a prospective employer's.

How do you do animation with Frames and AutoLayout?

This is a more specific question about views animation. Depending on the project and team focus they either would like to know how you handle basic animations or they want to know if you know how to work with advanced animations using Core Animation. Expected answer: Most likely talking about how to animate views with UIKit is sufficient enough. With frame-based views you simply change frames in UIView.animateWithDuration:animations: and then assign new frames to your views and that's it - the animation will be performed. It's almost the same thing with AutoLayout, but instead of changing frames directly you change your constraints and their constants in the animations: block of the UIView.animateWithDuration:animations: method and then call layoutIfNeeded() on the views you've changed.

What is AutoLayout? When and where would you use it?

This is a very common UI-related question on any interview. Virtually no interview will go without it. AutoLayout is one of the fundamental technologies that Apple pushed for for some time and now it is the de facto standard. Your interviewer is either expecting a very brief answer to get an understanding of whether you're versed in the topic or is going to drill down and ask you for all the details about it. Be prepared for both. Expected answer: AutoLayout is a technology that helps you define relation- ships between views, called constraints, in a declarative way, letting the frame- work calculate precise frames and positions of UI elements instead. AutoLay- out came as an evolution of previously used Frames and auto-resizing masks. Apple created it to support various screen resolutions and sizes of iOS devices. In a nutshell, using AutoLayout instead of setting view frames, you'll cre- ate NSLayoutConstraint objects either in code or use nibs or storyboards. NSLayoutConstraints describe how views relate to each other so that at runtime UIKit can decide what specific CGRect frames to set for each view. It will adjust to different screen sizes or orientations based on the "rules" you defined using constraints. The main things you'll be using working with AutoLayout are NSLayout- Relation, constant, and priority. • NSLayoutRelation defines the nature of a constraint between two UI items/views. It can be lessThanOrEqual, equal, or greaterThan- OrEqual. • constant defines constraint value. It usually defines things like the distance between two views, or the width of an item or margin, etc. • priority defines how high of a priority a given constraint should take. Constraints with a higher priority number take precedence over the oth- ers. Priority typically is used to resolve conflicting constraints. For example, when there could be an absence of content, we may want to align elements differently. In that scenario we'd create several constraints with different priority. Bonus points: Working with Apple's API for constraints in code is sometimes problematic and difficult. There are several different open source libraries out there that can help with it, such as Masonry and PureLayout, that dramatically simplify the process.

How do you debug and profile on iOS?

This is a very general question to elicit a single answer from a prospective candidate. To make things interesting, the candidate should be able to discuss instrumentation in iOS and crash logs. If you have a known bug in your application, it can be a good practice to let the developer open your environment and see how he/she navigates through its different instruments (CPU debugging, etc.).

What are compression resistance and content hugging priorities for?

This is an advanced question about AutoLayout typically asked along with other questions around constraints. Expected answer: Compression resistance is an AutoLayout constraint that defines how your view will behave while under the pressure of other constraints demanding its resizing. The higher compression resistance is, the less chance it's going to "budge" under the other constraint's pressure to compress it. Hugging priority is the opposite of compression resistance. This constraint defines how likely it it the view will grow under pressure from other constraints

What alternative ways of working with UI do you know?

This is an advanced question that interviewers ask to gauge how well informed you are of current trends in UI development. Expected answer: Talk about React and React-like trends in UI development on the web and iOS. There's React Native, which is a great alternative for declarative UI development, but unfortunately, it comes with JavaScript bag- gage. There are also libraries like ComponentKit, LayoutKit, and IGListKit that take a different approach from Apple's AutoLayout. 103 Red flag: You probably shouldn't say that you've never heard of other ap- proaches. It's fine if you never had a chance to try them out in real apps, though.

How do you work with UICollectionView?

This is the same questions as the one about UITableView. Your interviewer is trying to figure out if you've worked with more complex UIs for lists of items. 101 Expected answer: UICollectionView is the next step from UITableView and it was made to display complex layouts for lists of items - think a grid where you have two or more items in a row or a grid where each item could be a different size. Each item in a UICollectionView is a subclass of UI- CollectionViewCell. UICollectionView mimics UITableView in its API and has similar UICollectionViewDelegate and UICollection- ViewDataSource to perform the same functions. A very distinct feature of UICollectionView is that unlike UITableView it is using UICollectionViewLayout to help it lay out views it is going to display in its list.

Keychain

This is thought to store sensitive data in a secure way (recurrent examples are logins and passwords).

How do you mix AutoLayout with Frames?

This question could be asked by a team that has an existing application and they are trying to either migrate to AutoLayout fully or to support both Frames and AutoLayout at the same time for legacy reasons. Expected answer: AutoLayout and Frames can coexist together only in sce- narios when you're not mixing them up directly. Basically, you can have a superview lay out itself and its subviews using constraints and have one or all of those subviews position themselves with frames. Views that need to use frames will have to override the layoutSubviews() method where they can do the precise calculations for CGRects necessary to align things in them.

What are CGRect Frames? When and where would you use them?

This question is asked to learn if you have a background in building UI "the hard way" with using view position and size calculation. Before AutoLayout, Frames were used to position UI elements on the screen but these days there are other options you have to solve that problem. The interviewer is trying to figure out how advanced you are in UI rendering and how well you know a lower level of it. Expected answer: The simplest way to position views on the screen is to give them specific coordinates and sizes with CGRects. CGRect is a struct that represents a rectangle that a view is placed at. It has origin with x and y values, and size with width and height values. They represent the upper- left corner where the view starts to draw itself and the width and height of that view respectively. Frames are used to explicitly position views on the screen and have the most flexibility in terms of what and how you position views on the screen. But the disadvantage is that you have to take care of everything yourself (with great power comes great responsibility, you know), meaning even though you're in full control of how your UI is drawn on the screen, you will have to take care of all the edge cases and the different screen sizes and resolutions. A better option these days is AutoLayout. It helps you with layout positioning through constraints and sets specific frames for views for you. It makes your views scalable and adaptive to different screen sizes and resolutions.

What are the challenges in working with UI on iOS?

This question is typically asked to assess whether you understand that it's not that simple and straightforward to do UI on iOS anymore. Now we have mul- tiple screen sizes and resolutions, not to mention iPad and Multi-Tasking sup- port, where your views and view controllers can be displayed in various forms and formats. Expected answer: Show them that you are aware of the responsive and ad- justable nature of iOS UI. There are several things you as a developer need to be concerned with when developing UI for iOS: • multiple screen sizes/dimensions for iPhone 5, 6, 6 Plus, etc. • multiple screen sizes/dimensions for iPads • potential reusability of UIViews between iPhone and iPad • adaptability of your UI to resizable views used for multi-tasking feature on iPad (i.e., size classes) • UI performance, especially with dynamic content of various sizes in UITableViews and UICollectionViews Mentioning all of the concerns above show that you are aware of the issues. Also, it is good if you mention here that Apple has AutoLayout to address a lot of the challenges related to UI scalability and that it is a replacement of the previously used Frames and auto-resizing masks approach. These answers will likely make your interviewer steer toward a Frames versus AutoLayout discussion. Table views and collection views' performance is especially important for so- cial networking applications, for example. They typically have content of arbi- trary size posted by users that need to be displayed in lists. The challenge there 91 is to quickly calculate cell and other UI elements' sizes when the user scrolls the content quickly. Mentioning that will most likely prompt your interviewer to ask probing questions about Frames, AutoLayout, and UITableView/UICollectionVi

How do you work with UIScrollView?

UIScrollView is a very common UI component used in iOS apps. Interview- ers typically ask this question to gauge your level of experience working with either big, scrollable and zoomable content or gauge your level of understand- ing of UITableView and UICollectionView. Expected answer: UIScrollView is responsible for displaying content that is too big and cannot be fully displayed on the screen. It could be a big picture that the user can pinch to zoom or it could be a list where all of the items cannot be displayed on the screen at the same time. UIScrollView is a superclass of UITableView, UICollectionView, and UITextView; therefore, all of them get the same features as UIScrollView. When you work with UIScrollView, you define yourself as its delegate by adopting the UIScrollViewDelegate protocol. There are a lot of meth- ods that you get with that delegate but the main one you usually work with is scrollViewDidScroll(UIScrollView). In this method, you can do additional work when the user scrolls table view content, for example.

What is UIStackView? When would you use it and why

UIStackView is a powerful new way to lay out views of various sizes in a container into a column or a row. Interviewers ask this question to determine how up to date you are with the latest UI tools from Apple. UIStackView was introduced in iOS 9, but a surprising number of developers never heard about it. Expected answer: UIStackView is used to align views in a container and "stack" them one after another. If you ever worked with flexbox on the web or with linear layouts on Android, the concept will be familiar to you. Before iOS 9, you had to align your UI in a stack using constraints manually; it was very tedious and error prone, especially if you had to change the contents of your stack view at runtime. With UIStackView, it is as simple as a drag-and-drop in storyboards, and programmatically you add or remove views from the stack with just one command. UIStackView will take care of resizing for you. Note: Be very cautious of using UIStackView in a table view cell. Due to its dynamic sizing nature, it could negatively affect scrolling performance.

How do you work with UITableView?

UITableView is one of the most used and important UI classes in iOS appli- cations. You can expect this question in one form or another on pretty much any interview. The extent of your answer will vary, and if interviewers wants to dig deeper, they'll ask additional questions around table views. Expected answer: UITableView is a class that lets you display a list of static or dynamic content of variable or set heights with optional section grouping. Each row in a table is a UITableViewCell class or subclass. Table views and cells can be as complex or as simple as the application demands. Two of the biggest constraints on mobile devices are memory and performance. This is why table views are designed to dequeue and reuse UITableViewCells they are displaying instead of creating new objects as user scrolls. It helps avoid memory bloat and improves performance. When you work with UITableView you usually instantiate an instance of it and then implement UITableViewDelegate and UITableViewDataSource protocols. • UITableViewDelegate is responsible for calculating cells' and sec- tions' heights (unless it's done automatically with UITableViewAutomatic- Dimension) and for the other cell and section life cycle callbacks like tableView(UITableView, willDisplay: UITableViewCell, forRowAt: IndexPath)andtableView(UITableView, did- SelectRowAt: IndexPath). It also dequeues section views. • UITableViewDataSource is the source of data for the table. It pro- vides the model data your table is displaying. It is also responsible for dequeuing cells for specific indexPath.

How do you manage dependencies in iOS

Unlike other platforms, Apple does not officially provide any way to handle dependencies in an iOS project. As a de facto standard, CocoaPods is widely used among the iOS community. Dependencies for projects are specified in a single text file, called a Podfile, with which CocoaPods resolves dependencies between libraries, fetches the resulting source code, then links it together in an Xcode workspace to build your project. A more experienced candidate could certainly mention another alternative to CocoaPods, namely, Carthage, which is quite popular and has been written in Swift. Want to discuss this even further? Then start a discussion over the advantages of Carthage vs. CocoaPods.

What is View Controller? What is its lifecycle?

View Controllers are one of the core fundamental building units of Cocoa Touch applications. This question could be a part of or an expansion on the MVC question. Expected answer: View Controllers (VC) are the Controller part of the MVC triangle. They are re- sponsible for controlling the view. Every time you want to display more or less significantly complex pieces of UI, you would want to use a View Controller to handle the lifecycle and user interaction callbacks of that UI. In a nutshell, a View Controller is a simple subclass of UIViewController that has to have a view to draw the UI on. It is either attached to a UIWindow as the root View Controller of that window or managed by a UINavigationController or by another VC or system to be presented to the user. At the end of the day, when you develop iOS apps there are two main reasons you'd want to use View Controllers: • get lifecycle callback for the view that the VC is managing (when the view was loaded, displayed, hidden, etc.) • get handy built-in system integrations to present and dismiss VCs using UINavigationController, modal presentation, or parent/child con- tainment API View Controller lifecycle callbacks: 52 • loadView(): you can override this method if you'd like to create the view for your VC manually. • viewDidLoad(): this method is called once when your VC's view was loaded in memory for the first time. Do any additional setup and initial- izations here. Typically, this is the method where most of your custom view initialization and autolayout setup will go. Also, start your services and other async data-related stuff here. • viewWillAppear(): this method is called when the view is about to appear on the screen. It will be called after viewDidLoad and ev- ery subsequent time after view disappears from screen and then appears again. For example, when you present a view in a navbar it will call viewDidLoad and then viewWillAppear/viewDidAppear for that VC. Later, if you push a new VC on top of it, viewWillDisappear and viewDidDisappear will be called because it's no longer the fore- ground/top VC. Later still, if the user taps the Back button, viewWill- Appear and viewDidAppear for that first VC will be called because it becomes the top VC again. Use this method to do final UI customiza- tions, hook up UI observers, etc. • viewWillLayoutSubviews()iscalledrightbeforelayoutSubviews() in underlying UIView for that VC. It is rarely used to adjust your view positioning. • viewDidLayoutSubviews()iscalledrightafterlayoutSubviews() in underlying UIView for that VC. It is rarely used to adjust your view positioning. • viewDidAppear():thismethodiscalledrightaftertheviewwasshown on the screen and follows a viewWillAppear call. • viewWillDisappear() is called when the view is about to become "hidden" i.e. not the top view controller presented to the user (see exam- ple above). • viewDidDisappear() is called after viewWillDisappear and indi- cates that the view is "hidden". • didReceiveMemoryWarning() is called when the system is low on memory and needs to release additional resources. Deallocate as much as you can here. Don't go crazy about it, though, because nowadays phones are so powerful that memory warnings rarely happen. Additionally, View Controller, just like Views, can be initialized either pro- grammatically in code using init... constructor/initializer methods or loaded from a storyboard/xib file. In the former case, one of the initializer methods will be called and in the latter it will be via -initWithCoder.

What is the responder chain?

When an event occurs in a view, for example, a touch event, the view will fire the event to a chain of UIResponder objects associated with the UIView class. The first UIResponder is UIView itself. If it does not handle the event, it continues up the chain until UIResponder handles it. The chain will include UIViewControllers, parent UIViews, and their associated UIViewControllers. If none of those handles the event, then the UIWindow is asked if it can handle it, and, finally, if that doesn't handle the event, the UIApplicationDelegate is asked. Because this is all quite hierarchical, a candidate could be asked to draw this on a whiteboard. A diagram similar to Figure 3-2 will nail the problem.

What is the difference between using a delegate and notification?

You can think of delegates as being like a telephone call. You call up your buddy and specifically want to talk to her. You can say something, and she can respond. You can talk until you hang up the phone. Delegates, in much the same way, create a link between two objects, and you don't have to know what type the delegate is; it simply has to implement the protocol. On the other hand, NSNotification is like a radio station. It broadcasts messages to whoever is willing to listen. A radio station can't receive feedback from its listeners, unless it has a telephone (delegate). Listeners can ignore a message, or they can do something with it. NSNotification allows you to send a message to any object, but without a link between them to communicate back and forth. If you require this type of communication, you should probably implement a delegate; otherwise, NSNotification is simpler and easier to use, although it may get you into trouble.

What is Delegate pattern in iOS?

ike MVC, this is one of the fundamental Cocoa design patterns. This will be asked on every interview. Expected answer: Delegate pattern is a variation of Observer pattern where only one object can observe events coming from another object. That effectively makes Delegate pattern a one-to-one relationship. Delegates are com- monly used across iOS frameworks. Two of the arguably most commonly used examples would be UITableViewDelegate and UITableViewDataSource. These are both represented by a protocol that an object conforms to and UITableView uses the single object it is provided with to send messages/events. Unlike with Observer pattern, there can be only one delegate object. Delegation is sometimes abused by iOS developers. Be careful not to reas- sign your delegate object throughout the flow of your app because that might lead to unexpected consequences. The delegate/delegatee relationship is tightly coupled.

What is the difference between viewDidLoad and viewDidAppear? Which one would you use to load data from a remote server and display it in the screen?

viewDidLoad() is called only one time, when the view controller has been initially loaded into memory. Generally, when we want to instantiate variables and build views that will be alive during the entire life cycle of the view controller, we do it here. However, the view is still not visible! viewDidAppear() is called when the view is first prompted into the screen. This method can actually be called several times during the life cycle of a view controller. Let's think, for example, when a modal view controller is loaded and later dismissed. The view already has been loaded, but it will appear twice as a result. In this method, we typically perform layout actions, such as drawing into the UI, presenting modal screens, etc. This is where you want to instantiate any instance variables and build any views that live for the entire life cycle of this view controller. However, the view is usually not visible at this point. To answer the question, you want to load data from a remote server in the method viewDidLoad. That way, it is loaded once, not every time the view appears. To follow up with a candidate, you could ask him/her what the effect of retaining things in the viewDidAppear is. The effect is that very likely memory leaks will occur, if the items are not released after a view has disappeared.

Can you list and explain the different types of iOS application states?

• Not running: The app has not been launched or was running but was terminated by the system. • Inactive: The app is running in the foreground but is currently not receiving events. (It may be executing other code, however.) An app usually stays in this state only briefly, as it transitions to a different state. • Active: The app is running in the foreground and is receiving events. This is the normal mode for foreground apps. • Background: The app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state. For information about how to execute code while in the background, see Background Execution https:// developer.apple.com/library/archive/documentation/ iPhone/Conceptual/iPhoneOSProgrammingGuide/ TheAppLifeCycle/TheAppLifeCycle.html. • Suspended: The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code. When a low-memory condition occurs, the system may purge suspended apps without notice, to make more space for the foreground app.

What is the difference between an App ID and a Bundle ID in iOS

A Bundle ID is used to precisely identify a single app. The Bundle ID string must be a uniform type identifier (UTI) that contains only alphanumeric characters (A-Z, a-z, 0-9), hyphens (-), and periods (.). The string should be in reverse DNS format. An App ID is a two-part string used to identify one or more apps froma single development team. The string consists of a Team ID and a Bundle ID search string, with a period (.) separating the two part. The Team ID is supplied by Apple and is unique to a specific development team, while the Bundle ID search string is supplied by you to match either the Bundle ID of a single app or a set of Bundle IDs for a group of apps. Why would Apple choose such a confusing nomenclature is a secret nobody has revealed yet.


Set pelajaran terkait

141- African American History Final Exam/ Test 1

View Set

Completing the Application, Underwriting and Delivering Policy

View Set

Artistic Achievements of the Renaissance

View Set

Chapter 6 - Integumentary System - Recharge

View Set