© Enrique López Mañas 2019
Enrique López Mañas100 Questions and Answers to Help You Land Your Dream iOS Jobhttps://doi.org/10.1007/978-1-4842-4273-5_3

3. We Need That Person on Board to Do Great Things!

Enrique López Mañas1 
(1)
München, Bayern, Germany
 

This chapter is dedicated to upper-level iOS engineers—typically, those with several years of experience and who have worked on a wide range of projects with a greater number of requirements. Remember that experience must be combined with practical analytical and problem-solving skills. Employers won’t want to hire a candidate who just read this book and memorized it, for example.

Especially with the questions in this chapter, you want to promote discussion and the exchange of opinions. Sometimes, there is a single solution to real-time problems, and most of these solutions involve a trade-off. You may have to give up in performance what you gain in code usability, etc.

Senior developers also require the leadership and motivational skills to lead a team. This book does not cover possible questions or methods to identify those skills, but I am sure the reader already has some idea about how to identify these. Senior developers must be comfortable and self-confident when discussing any topic, and they should be able to embrace change. They should have an entrepreneurial aura about them. They are facilitators rather than bosses and should encourage independence and freethinking.

Question 67: 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.

Question 68: What is method swizzling? When would you use it?

Method swizzling is the process of changing the implementation of an existing selector. It’s a technique made possible by the fact that method invocations in Objective-C can be changed at runtime, by changing how selectors are mapped to underlying functions in a class’s dispatch table.

For example, let’s say we wanted to track how many times each view controller is presented to a user in an iOS app. Each view controller could add tracking code to its own implementation of viewDidAppear:, but that would make for a ton of duplicated boilerplate code. Subclassing would be another possibility, but it would require subclassing UIViewController, UITableViewController, UINavigationController, and every other view controller class—an approach that would also suffer from code duplication.

Question 69: Take three objects: a grandparent, parent, and child. The grandparent retains the parent, the parent retains the child, and the child retains the parent. The grandparent releases the parent. What happens?

A retain cycle happens. Because they are retained, it will not be possible to release them from memory. This can be solved by making one of the references weak.

Question 70: What are two separate and independent reasons why-retainCount should never be used in shipping code?

You should never use -retainCount , because it never tells you anything useful. The implementation of the Foundation and AppKit/UIKit frameworks is opaque. You don’t know what’s being retained, why it’s being retained, who’s retaining it, when it was retained, and so on. Following are examples of when to use -retainCount:
  • [NSNumber numberWithInt:1] now has a retainCount of 9223372036854775807. If your code was expecting it to be 2, your code has now broken.

  • You’d think that @"Foo" would have a retainCount of 1. It doesn’t. It’s 1152921504606846975.

  • You’d think that [NSString stringWithString:@"Foo"] would have a retainCount of 1. It doesn’t. Again, it’s 1152921504606846975.

Basically, because anything can retain an object (and, therefore, alter its retainCount), and because you don’t have the source to most of the code that runs an application, an object’s retainCount is meaningless. If you’re trying to track down why an object isn’t getting deallocated, use the leaks tool in Instruments. If you’re trying to track down why an object was deallocated too soon, use the zombies tool in Instruments. But don’t use -retainCount. It’s a truly worthless method.

Question 71: How does an autorelease pool work at the runtime level?

Every time -autorelease is sent to an object, it is added to the innermost autorelease pool. When the pool is drained, it simply sends -release to all the objects in the pool.

Autorelease pools are simply a convenience that allows you to defer sending -release until “later.” That “later” can happen in several places, but the most common in Cocoa GUI apps is at the end of the current run loop cycle.

Question 72: Which is faster: to iterate through an NSArray or an NSDictionary?

When the order of the items in the collection is not important, sets offer better performance for finding items in the collection. The reason is that a set uses hash values to find items (like a dictionary), while an array has to iterate over its entire contents to find a particular object.

Figure 3-1 shows a very representative image of the Apple documentation stating this.
../images/475684_1_En_3_Chapter/475684_1_En_3_Fig1_HTML.png
Figure 3-1

Object collection framework in iOS

Question 73: Which is faster: to iterate through an NSArray or an NSSet?

NSArray is faster than NSSet for simply holding and iterating. On the lower end, it is as much as 50% faster for constructing and, at the higher end, as much as 500% faster for iterating. If you are required only to iterate content, don’t use NSSet.

Question 74: Do you have to implement all the declarations from an adopted protocol?

No. If a method is declared as @optional , it does not have to be implemented.
@protocol MyProtocol
- (void)requiredMethod;
@optional
- (void)anOptionalMethod;
- (void)anotherOptionalMethod;
@required
- (void)anotherRequiredMethod;
@end

If a developer is asked to identify a risk with this approach, he/she should be able to advance the idea that if a method in a protocol is marked as optional, you must check whether an object implements that method, before attempting to call it.

Question 75: What is a shortcut for calling alloc and init?

alloc and init can generally be called like this:
[[Class alloc] init]
In some other pieces of code and in the literature, we can also find the following:
[Class new]

Originally in Objective-C, objects were created with new. As the OpenStep/Cocoa framework evolved, designers formed the opinion that allocating the memory for an object and initializing its attributes were separate concerns and, thus, should be separate methods (for example, an object might be allocated in a specific memory zone). So, the alloc-init style of object creation came into favor. Basically, new is old and almost-but-not-quite deprecated. Therefore, you’ll see that Cocoa classes have a lot of init methods but almost never any custom new methods.

Question 76: What kind of pointer can help to safely avoid a memory leak?

Smart pointers can be very helpful in automating the bookkeeping of object lifetimes. A smart pointer is a class that wraps a “raw” (or “bare”) C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way.

Smart pointers should be preferred over raw pointers. If you feel you must use pointers (first consider if you really do), you would normally want to use a smart pointer, as this can alleviate many of the problems with raw pointers, mainly, forgetting to delete the object and leaking memory.

Question 77: What can help to prevent an out-of-memory crash if you have a long-running execution loop?

Here, one key is memory leaks. Make sure that the memory is being cleaned and you are not keeping any references that prevent an object from being collected. Look also for the applicationWillTerminate message in your app delegate. This is called if your app is terminated by the system (e.g., owing to low memory) but not if the user leaves the app in the usual way, by pressing the home key.

Question 78: 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.

Question 79: What is KVC and KVO? What is an example of using KVC to set a value?

KVC stands for “key-value coding.” It’s a mechanism by which an object’s properties can be accessed using strings at runtime, rather than having to statically know the property names at development time. KVO stands for “key-value observing” and allows a controller or class to observe changes to a property value.

For example, if there is a property name on a class
@property (nonatomic, copy) NSString *name;
we can access it using KVC, as follows:
NSString *n = [object valueForKey:@"name"]
and we can modify its value by sending it the following message:
[object setValue:@"Mary" forKey:@"name"]

Question 80: What mechanisms does iOS provide to support multi-threading?

There are a bunch of different techniques that we can use in iOS to provide multi-threading to an application.
  • NSThread creates a new low-level thread that can be started by calling the start method.

  • NSOperationQueue allows a pool of threads to be created and used to execute NSOperations in parallel. NSOperations can also be run on the main thread by asking NSOperationQueue for the mainQueue.

  • Grand Central Dispatch (GCD) is a modern feature of Objective-C that provides a rich set of methods and APIs to use to support common multi-threading tasks. GCD provides a way to queue tasks for dispatch on either the main thread, a concurrent queue (tasks are run in parallel), or a serial queue (tasks are run in FIFO order).

Question 81: 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.
../images/475684_1_En_3_Chapter/475684_1_En_3_Fig2_HTML.jpg
Figure 3-2

Responder chain flow in iOS

Question 82: 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.

Question 83: How would you securely store private user data offline on a device? What other security best practices should be taken?

This question should trigger a conversation with the candidate about best practices and frameworks. A well-versed candidate will be able to talk about Keychain, Touch ID, and 1password. In addition, general conversations about network security (using SSL connections, using Charles for debugging, and so forth) can lead to interesting places.

Question 84: Are SQL injection attacks valid in iOS? How would you prevent them?

SQL injection attacks are very likely to occur in iOS. There are a few ways to prevent them. One is to use parameterized queries.

Question 85: What are the common reasons for app rejections in the App Store?

I particularly like this question, although is not technical. A person who has been in the iOS development arena for a while will likely have witnessed several rejections. From these, you can elicit interesting stories from the candidate and also analyze how he/she approaches and solves those problems.

Question 86: How can you make a code snippet thread safe?

You can use the keyword @synchronized . This will automatically make a thread safe.

There is a very interesting approach that few engineers might be familiar with, and if a candidate can mention it, he/she is definitely on his/her game: making all objects immutable, so that they cannot be modified.

Question 87: Why should we release the outlets in viewDidUnload?

viewDidUnload is strictly used for releasing IBOutlets with retain properties. The reason for this has to do with the fact that UIViewController has a view property that it retains. That view property itself retains references to all of its subviews. These subviews are exactly what you are retaining inside these outlet properties. The problem lies in that these subviews have an “extra” retain.

The goal of - viewDidUnload is to clear up unnecessary memory usage. When -viewDidUnload is called, the view property has already been released, which releases the top level UIView, along with all its subviews. Because we have retained some of these subviews, however, they linger in memory, and we want to release them, because they will no longer be used. New copies of these subviews will be created when (if) the view is reloaded. The properties are also set to nil, strictly, so we don’t have pointers pointing to deallocated memory.

Question 88: What is the difference between a shallow copy and a deep copy?

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicate.

Question 89: How would you pass an unknown type as a parameter?

You could use (id).
-(void) fooMethod:(id)unknownTypeParameter {
    if( [unknownTypeParameter isKindOfClass:[Animal Class]]) {
        Animal *referanceObj = (Animal *) unknownTypeParameter;
        referanceObj.noOfLegs = 4;
    }
}

Question 90: What is deinitializer and how it is written in Swift?

A deinitializer is declared immediately before a class instance is deallocated. You write a deinitializer with the deinit keyword. A deinitializer is written without parentheses, and it does not take any parameters. It is written as follows:
deinit {
        // perform the deinitialization
}

Question 91: What is optional chaining?

The process of querying—calling properties, subscripts, and methods on an optional that may be nil—is defined as optional chaining. Optional chaining return two values:
  • If the optional contains a value, calling its related property, methods, and subscripts returns value.

  • If the optional contains a nil value, all its related properties, methods, and subscripts return nil.

Because multiple queries to methods, properties, and subscripts are grouped, failure of one chain will affect the entire chain and result in a nil value.

Question 92: What is the Fallthrough statement? What does it do?

Fallthrough “falls through” to the next case, not to the next matching case. The concept is inherited from C switch statements, in which each case may be thought of as a go-to destination label, and the switch statement brings execution to the first matching one.

Question 93: What are lazy stored properties and when are they useful?

Lazy stored properties are used for a property whose initial values are 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 of a property relies on outside factors whose values are unknown.

Question 94: Have you heard of Handoff?

Handoff is a new feature introduced with iOS 8 and OS X Yosemite. Handoff allows you to continue an activity uninterrupted when you switch from one device to another, without the need to reconfigure either device.

Question 95: Can you have more UIWindows in iOS?

It is a rare case, although it is possible. For example, this happens when you have a UIAlertView in a separate window.

Question 96: What is Metal?

Metal is a low-level, less portable, more optimized graphics layer for doing the same kind of things you would with OpenGL (and OpenCL) or Direct3D, that is, 3D graphics rendering and parallel GPU programming. Metal attempts to lower the amount of overhead required for performance reasons, as well as reduce CPU bottlenecks.

Question 97: Can you come up with strategies to increase efficiency in your networking?

An experienced developer should know some techniques not available by default in iOS. This will up your game.

You could discuss such topics as latency gauging (evaluating the type of network you are connected to, in order to make a decision about the data transmission), batching (packing requests together and sending them along when they are a representative group—something done in many analytics SDKs), pre-fetching (downloading information when the device is idle or the Internet connection is strong), exponential back-off (if a connection fails, wait for exponentially increasing intervals before making the next request), caching mechanisms, usage of Last-Modified headers…

Question 98: What is the most complex problem you had to solve at your previous job?

This question will reveal skills the candidate possesses that are unrelated directly to iOS knowledge but equally important. This can direct you to discuss the problems of growing an application, escalating a system, how to make software grow sustainably in the long term, how to grow teams and make them work efficiently, and frameworks the candidate has used to solve problems.

Question 99: What is an autorealease pool?

The NSAutoreleasePool class is used to support Cocoa’s reference-counted memory management system. An autorelease pool stores objects that are sent a release message when the pool itself is drained. Also, if you use automatic reference counting, you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks.

Question 100: What is the class hierarchy from a UIButton to an NSObject?

UIButton inherits from UIControl, UIControl inherits from UIView, UIView inherits from UIResponder, UIResponder inherits from the root class NSObject : UIButtonUIControlUIViewUIResponderNSObject.

Can I ask you for a favor?

If you enjoyed this book and/or found it informative or otherwise useful, I’d really appreciate it if you posted a short review on Amazon. I read all the reviews, so that I can continue to write about what people are interested in.

Feedback, corrections, questions, doubts, suggestions? Feel free to contact me via e-mail at [email protected].

Thank you for your support!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.253.62