Thursday 13 October 2016

iOS Interview Questions For Senior Developers

  1. What was the latest version of iOS you worked with? what do you like about it and why?
  2. Have you worked with Swift? What do you like about it? What you don’t like?
  3. How memory management is handled on iOS?
  4. What do you know about singletons? Where would you use one and where you wouldn't?
  5. Could you explain what is the difference between Delegate and KVO?
  6. How do you usually persist data on iOS?
  7. How do you typically do networking?
  8. How do you serialize data on iOS (JSON from the web or local app data to Core Data and other storages) ?
  9. What design patterns do you know and use on iOS?
  10. What is Autolayout?
  11. How do you handle async tasks?
  12. How do you manage dependencies?
  13. How do you debug and profile things on iOS?
  14. Do you code review?
  15. Do you test your code? What do you do to make your code testable?

Let’s go through each of them individually to get a sense what answers for each tell us about the interviewee.

1. What was the latest version of iOS you worked with? What do you like about it and why?

The purpose of this question is to inquire if the interviewee actually keeps up with the latest development from Apple.
Expected answer:  he/she tells you what the latest version of the system is and what he/she has worked with lately. And tells you about one of the new features of the system that he/she is excited about (i.e. I love new multitasking on iPad because it’s going to make user experience way better and opens up a lot of opportunities for us developers to build new cool things, etc.).

2. Have you worked with Swift? What do you like about it? What you don’t like?

This question will give you a sense of several things:
  • is he cautious with using something as unstable as Swift. For example 2.0/2.1 releases broke a lot of things/libraries and a senior developer would think twice about using Swift on a production application. Because a lot of libraries and frameworks necessary for production ready iOS development either do not exist yet in pure Swift or do not work anymore with newer versions of the language (as of today - 11/11/15).
  • whether the developer is bold enough to play with the cutting edge stuff
  • what’s his long terms plans and expectations (is he optimistic or pessimistic or somewhere in between)

Expected answer: be cautious, use Swift along with Objective-C for now and move to pure Swift down the road in several years when it and the ecosystem of libraries around it matures enough.

3. How memory management is handled on iOS?

This question will give you an idea of how long the person was working with iOS, whether she/he’s a newcomer who’s worked only with ARC or he/she’s worked with manual retain count (MRC) and has a deeper knowledge/experience with memory management on iOS.
Expected answer: it is great if interviewee knows MRC but it is not necessary. More important that he/she understands `strong``weak``assign`, etc. directives on properties and can confidently tell you what those directives imply and how it’s handled with blocks.

4. What do you know about singletons? Where would you use one and where you wouldn't?

This is a typical objective oriented programming question. In case of iOS you can get a feel of how the interviewee is using it in his/her apps. You’ll be able to weed out those people who came from Java/PHP and such and use it as a “global” store or something similar.
Expected answer:  singletons should be avoided and used only for objects that need to be shared throughout your application for same reason. It should be used carefully, instantiated lazily, if it’s possible, and passed into other objects as a dependency using Inversion of Control and Dependency Injection principles.Red flag: is when the interviewee talks about global variables and stores.

5. Could you explain what is the difference between Delegate and KVO?

With this question you are assessing their knowledge of different types of messaging patterns used in iOS. Senior developer should’ve used both of those many times in his/her applications.
Expected answer: Both are ways to have relationships between objects. Delegation is a one to one relationship where one object implements a delegate protocol and another uses it and sends messages to assuming that those methods are implemented since the receiver promised to comply to the protocol. KVO is many-to-many relationship where one object could broadcast a message and one or multiple other objects can listen to it and react.

6. How do you usually persist data on iOS?

This will tell you if they just played with rudimentary ways to store data locally on iOS like `NSUserDefaults`, `Plists`, disk file storage, etc. or if they have used more advanced storages like `Core Data` and `Realm`. Ideally they should know when it is appropriate to use all of the above persistence tools.
Expected answer:  A senior developer should at least be able to tell you when it is appropriate to use `NSUserDefaults`, `Core Data`, and disk file storage. `Core Data` is what you’re expecting them to explain you the most. Other possible options are `Realm` and similar third party (non-Apple) solutions but make sure they know why they would want to use them instead of `Core Data`.With `Core Data` they should be able to explain how it works and how it’s different from `SQLite` (i.e. it’s an object graph rather than a relational database, etc.). 

7. How do you typically do networking?

Networking is a vital part of almost any application these days. In fact the majority of them is useless without an internet connection. Any decent iOS developer should know how to initiate various networking requests (GET, POST, PUT, DELETE, etc.) using Apple’s frameworks or third party tools such as `AFNetworking`.
Expected answer: Interviewee should be able to explain how to do not just basic networking but more advanced things like HTTP headers and token handling. But in general look for developers who use either `AFNetworking` or `Alamofire` or similar. The reason is these libraries are used very extensively by iOS community and are utilized in many other tools. Senior developer should be able to utilize that instead of reinventing a wheel.

8. How do you serialize data on iOS (JSON from the web or local app data to Core Data and other storages) ?

Data serialization is an important task for every iOS application. JSON is defacto standard of data serialization on the web and every developer should know how to effectively work with it without spending a lot of time writing boilerplate code. Same applies to data serialization for local storage. It can be handled in multiple ways but a good developer should at least be aware of the challenges with these tasks. Expected answer: This is a tricky question. A naive developer would say that he/she parses JSON data using Apple’s `NSJSONSerialization` and then takes the resulting dictionary and assigns the data from each key to respective properties on his/her model object. This is not what you expect a senior developer to tell you. Senior developer should be aware of the issues that could arise with data serialization such as data validation and conversion. A good answer would be clear understanding that in general there are two types of data serialization: JSON to domain model, and domain model to persistence. Utilization of pods like Mantle or ObjectMapper or a similar library/pod is expected. 

9. What design patterns do you know and use on iOS?

This could be a very simple or a very complicated answer. Every iOS developer should know about MVC but if you’re looking for a senior developer than he/she should have a lot of patterns and best practices on how to organize code under his belt.
Expected answer: at least MVVM. This is the holy grail that saves iOS developers fromMassive View Controllers. Senior developer should be able to explain you what MVVM is, why it’s better than MVC, and should be able to tell you what other patterns he/she uses along with MVVM (Inversion of Control, Dependency Injection, etc.).Red flags: if interviewee tells you that he uses only MVC because Apple said so and he/she never tried MVVM than that person is definitely not a senior iOS developer.

10. What is Autolayout?

Autolayout is one of the technologies on iOS that helps us build scalable UI that can be used on many devices of different shape and size. This is a must know for any iOS developer especially for a senior one.
Expected answer: do not expect proficiency with this technology but the interviewee should be able to tell you when and how he/she would use it and what benefits it gives them (i.e. scalable adjustable declarative UI).

11. How do you handle async tasks?

Asynchronous programming is a vital part of any iOS application. Networking, local storage, and other heavy computation tasks should be handled in the background to avoid blocking UI and having users wait or system kill your application.
Expected answer: answers to this questions may vary from NSOperations and GCD to Promises and RAC. A good developer knows multiple ways to execute async operations and knows when they are necessary (i.e. with networking, local persistence, etc. see above). From a senior developer though we expect a more higher and broader level of tools they use such as ReactiveCocoa and PromiseKit.

12. How do you manage dependencies?

Dependencies management is a vital but daunting task. It was very difficult and error prone to do before but these days we have several tools to help us out with it. Every iOS dev should know how to handle dependencies and collaborate with other teammates.
Expected answer: CocoaPods and/or Carthage.Red flags: if the say that they don’t use any dependency manager and just copy files to the project folder. Also a red flag if the use git submodules (it leads to project configuration issues and inconsistencies between local setups for different developers on the team).

13. How do you debug and profile things on iOS?

No one writes perfect code and debugging and profiling is one of the tools that we use to figure out the right technical solution. On iOS we have all the typical “manual” debugging tools such as `NSLog`/`print` functions to output things in console. But Apple also provides us with more advanced variety of tools and instruments to help with identifying where problems lie.
Expected answer: every iOS developer should be able to explain how he/she would use breakpoints and logs to get the runtime data but from a senior developer you should expect to hear things about Instruments and Crash Logs.

14. Do you code review?

Code reviews is one of the most effective development methodologies. It helps understand the problem better, share knowledge, share techniques, catch bugs, share ownership of the codebase, etc. This style of development is not for everyone but every development should be able to do that effectively.
Expected answer: senior developer should be more or less proficient in this type of code collaboration. Again, this is not for everyone (depends on personality, compatibility and other factors), but that is a skill that should show you if the candidate is able to work with other people and communicate his thoughts and ideas clearly to another teammate.

15. Do you test your code? What do you do to make your code testable?

This is embarrassing but we admit that we don’t do testing as much as we should. We know we really really should do it more. We are talking about Unit Testing and Integration Testing specifically here.
Expected answer: there is only one right answer here: either they do it or they wish they would. In general iOS community isn’t as big on testing as say Ruby community. Partially it is due to inherited lack of testing culture and partially due to lack of good tools for testing but things seems to be improving on that front.

Wednesday 12 October 2016

Iphone Interview Questions And Answers - Freshers & Experienced

What is iPhone? - IPhone is a combination of internet and multimedia enabled smart phone developed by Apple Inc.....
What are the features of iphone 3gs? - Video: Videos can be edited, shared. High quality VGA video can be shot in portrait or landscape......
What is iphone OS? - iPhone OS runs on iPhone and iPod touch devices........
What is iphone sdk? - iPhone SDK is available with tools and interfaces needed for developing, installing and running custom native applications.....
What is iphone architecture? - It is similar to MacOS X architecture.....
What is iphone reference library? - iPhone reference library is a set of reference documents for iPhone OS.....
What are sensors in iphone? - The proximity sensor immediately turns off the display when the iPhone is lifted to ear....
What are the location services? - Applications such as Maps, camera and compass are allowed to use the information from cellular..
Functionality of accelerometer of an iphone - iPhone responds to motion using a built-in accelerometer.....
Applications that can be used with iphone - Technology, Entertainment and Design(TED) : Allows to watch and listen to world’s most fascinating people have to say.

Thursday 6 October 2016

Ready For Your IOS Interview And Answer

The big day is coming up. Whether it’s a phone, online or in person interview it is always a little bit stressful. So, to ease the stress you did some prep work- completed the homework on the company you are interviewing with, stalked the hiring manager and half of the engineering team at the company of your choice on linkedin & github, you brushed up on some of the skills and knowledge you haven’t used in a while- you are ready to go.



Question 1

On a UITableViewCell constructor:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
What is the reuseIdentifier used for?
The reuseIdentifier is used to indicate that a cell can be re-used in a UITableView. For example when the cell looks the same, but has different content. The UITableView will maintain an internal cache of UITableViewCell’s with the reuseIdentifier and allow them to be re-used when dequeueReusableCellWithIdentifier: is called. By re-using table cell’s the scroll performance of the tableview is better because new views do not need to be created.

Question 2

Explain the difference between atomic and nonatomic synthesized properties?
Atomic and non-atomic refers to whether the setters/getters for a property will atomically read and write values to the property. When the atomic keyword is used on a property, any access to it will be “synchronized”. Therefore a call to the getter will be guaranteed to return a valid value, however this does come with a small performance penalty. Hence in some situations nonatomic is used to provide faster access to a property, but there is a chance of a race condition causing the property to be nil under rare circumstances (when a value is being set from another thread and the old value was released from memory but the new value hasn’t yet been fully assigned to the location in memory for the property).

Question 3

Explain the difference between copy and retain?
Retaining an object means the retain count increases by one. This means the instance of the object will be kept in memory until it’s retain count drops to zero. The property will store a reference to this instance and will share the same instance with anyone else who retained it too. Copy means the object will be cloned with duplicate values. It is not shared with any one else.

Question 4

What is method swizzling in Objective C and why would you use it?
Method swizzling allows the implementation of an existing selector to be switched at runtime for a different implementation in a classes dispatch table. Swizzling allows you to write code that can be executed before and/or after the original method. For example perhaps to track the time method execution took, or to insert log statements
#import "UIViewController+Log.h"
@implementation UIViewController (Log)
    + (void)load {
        static dispatch_once_t once_token;
        dispatch_once(&once_token,  ^{
            SEL viewWillAppearSelector = @selector(viewDidAppear:);
            SEL viewWillAppearLoggerSelector = @selector(log_viewDidAppear:);
            Method originalMethod = class_getInstanceMethod(self, viewWillAppearSelector);
            Method extendedMethod = class_getInstanceMethod(self, viewWillAppearLoggerSelector);
            method_exchangeImplementations(originalMethod, extendedMethod);
        });
    }
    - (void) log_viewDidAppear:(BOOL)animated {
        [self log_viewDidAppear:animated];
        NSLog(@"viewDidAppear executed for %@", [self class]);
    }
@end

Question 5

What’s the difference between not-running, inactive, active, background and suspended execution 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 though.) 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.
  • 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.

Question 6

What is a category and when is it used?
A category is a way of adding additional methods to a class without extending it. It is often used to add a collection of related methods. A common use case is to add additional methods to built in classes in the Cocoa frameworks. For example adding async download methods to theUIImage class.

Question 7

Can you spot the bug in the following code and suggest how to fix it:
@interface MyCustomController : UIViewController  

@property (strong, nonatomic) UILabel *alert;  

@end  

@implementation MyCustomController  

- (void)viewDidLoad {
     CGRect frame = CGRectMake(100, 100, 100, 50);
     self.alert = [[UILabel alloc] initWithFrame:frame];
     self.alert.text = @"Please wait...";
     [self.view addSubview:self.alert];
      dispatch_async(
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
        ^{
           sleep(10);
           self.alert.text = @"Waiting over";
        }
    ); 
}  

@end  
All UI updates must be done on the main thread. In the code above the update to the alert text may or may not happen on the main thread, since the global dispatch queue makes no guarantees . Therefore the code should be modified to always run the UI update on the main thread
dispatch_async(        
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
    ^{
      sleep(10);
      dispatch_async(dispatch_get_main_queue(), ^{
         self.alert.text = @"Waiting over";
      });
}); 

Question 8

What is the difference between viewDidLoad and viewDidAppear? Which should you use to load data from a remote server to display in the view?
viewDidLoad is called when the view is loaded, whether from a Xib file, storyboard or programmatically created in loadViewviewDidAppear is called every time the view is presented on the device. Which to use depends on the use case for your data. If the data is fairly static and not likely to change then it can be loaded in viewDidLoad and cached. However if the data changes regularly then using viewDidAppear to load it is better. In both situations, the data should be loaded asynchronously on a background thread to avoid blocking the UI.

Question 9

What considerations do you need when writing a UITableViewController which shows images downloaded from a remote server?
This is a very common task in iOS and a good answer here can cover a whole host of knowledge. The important piece of information in the question is that the images are hosted remotely and they may take time to download, therefore when it asks for “considerations”, you should be talking about:
  • Only download the image when the cell is scrolled into view, i.e. whencellForRowAtIndexPath is called.
  • Downloading 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 need to check if that cell is still in the view or whether it has been re-used by another piece of data. If it’s been re-used then we should discard the image, otherwise we need to switch back to the main thread to change the image on the cell.
Other good answers will go on to talk about offline caching of the images, using placeholder images while the images are being downloaded.

Question 10

What is a protocol, how do you define your own and when is it used?
A protocol is similar to an interface from Java. It defines a list of required and optional methods that a class must/can implement if it adopts the protocol. Any class can implement a protocol and other classes can then send messages to that class based on the protocol methods without it knowing the type of the class.
@protocol MyCustomDataSource
- (NSUInteger)numberOfRecords;
- (NSDictionary *)recordAtIndex:(NSUInteger)index;
@optional
- (NSString *)titleForRecordAtIndex:(NSUInteger)index;
@end
A common use case is providing a DataSource for UITableView or UICollectionView.

Question 11

What is KVC and KVO? Give 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 string's 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.
Let's say there is a property name on a class:
@property (nonatomic, copy) NSString *name;
We can access it using KVC:
NSString *n = [object valueForKey:@"name"]
And we can modify it's value by sending it the message:
[object setValue:@"Mary" forKey:@"name"]

Question 12

What are blocks and how are they used?
Blocks are a way of defining a single task or unit of behavior without having to write an entire Objective-C class. Under the covers Blocks are still Objective C objects. They are a language level feature that allow programming techniques like lambdas and closures to be supported in Objective-C. Creating a block is done using the ^ { } syntax:
 myBlock = ^{
    NSLog(@"This is a block");
 }
It can be invoked like so:
myBlock();
It is essentially a function pointer which also has a signature that can be used to enforce type safety at compile and runtime. For example you can pass a block with a specific signature to a method like so:
- (void)callMyBlock:(void (^)(void))callbackBlock;
If you wanted the block to be given some data you can change the signature to include them:
- (void)callMyBlock:(void (^)(double, double))block {
    ...
    block(3.0, 2.0);
}

Question 13

What mechanisms does iOS provide to support multi-threading?
  • NSThread creates a new low-level thread which can be started by calling the start method.
NSThread* myThread = [[NSThread alloc] initWithTarget:self
                                        selector:@selector(myThreadMainMethod:)
                                        object:nil];
[myThread start]; 
  • 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.
NSOperationQueue* myQueue = [[NSOperationQueue alloc] init];
[myQueue addOperation:anOperation]; 
[myQueue addOperationWithBlock:^{
   /* Do something. */
}];
  • GCD or Grand Central Dispatch is a modern feature of Objective-C that provides a rich set of methods and API's to use in order 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).
dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(myQueue, ^{
    printf("Do some work here.\n");
});

Question 14

What is the Responder Chain?
When an event happens in a view, for example a touch event, the view will fire the event to a chain of UIResponder objects associated with the UIView. The first UIResponder is the UIViewitself, if it does not handle the event then it continues up the chain to until UIResponder handles the event. The chain will include UIViewControllers, parent UIViews and their associatedUIViewControllers, if none of those handle the event then the UIWindow is asked if it can handle it and finally if that doesn't handle the event then the UIApplicationDelegate is asked.
If you get the opportunity to draw this one out, it's worth doing to impress the interviewer:
enter image description here

Question 15

What's the difference between using a delegate and notification?
Both are used for sending values and messages to interested parties. A delegate is for one-to-one communication and is a pattern promoted by Apple. In delegation the class raising events will have a property for the delegate and will typically expect it to implement some protocol. The delegating class can then call the delegates protocol methods.
Notification allows a class to broadcast events across the entire application to any interested parties. The broadcasting class doesn't need to know anything about the listeners for this event, therefore notification is very useful in helping to decouple components in an application.
[NSNotificationCenter defaultCenter] 
        postNotificationName:@"TestNotification" 
        object:self];

Question 16

What's your preference when writing UI's? Xib files, Storyboards or programmaticUIView?
There's no right or wrong answer to this, but it's great way of seeing if you understand the benefits and challenges with each approach. Here's the common answers I hear:
  • Storyboard's and Xib's are great for quickly producing UI's that match a design spec. They are also really easy for product managers to visually see how far along a screen is.
  • Storyboard's are also great at representing a flow through an application and allowing a high-level visualization of an entire application.
  • Storyboard's drawbacks are that in a team environment they are difficult to work on collaboratively because they're a single file and merge's become difficult to manage.
  • Storyboards and Xib files can also suffer from duplication and become difficult to update. For example if all button's need to look identical and suddenly need a color change, then it can be a long/difficult process to do this across storyboards and xibs.
  • Programmatically constructing UIView's can be verbose and tedious, but it can allow for greater control and also easier separation and sharing of code. They can also be more easily unit tested.
Most developers will propose a combination of all 3 where it makes sense to share code, then re-usable UIViews or Xib files.

Question 17

How would you securely store private user data offline on a device? What other security best practices should be taken?
Again there is no right answer to this, but it's a great way to see how much a person has dug into iOS security. If you're interviewing with a bank I'd almost definitely expect someone to know something about it, but all companies need to take security seriously, so here's the ideal list of topics I'd expect to hear in an answer:
  • If the data is extremely sensitive then it should never be stored offline on the device because all devices are crackable.
  • The keychain is one option for storing data securely. However it's encryption is based on the pin code of the device. User's are not forced to set a pin, so in some situations the data may not even be encrypted. In addition the users pin code may be easily hacked.
  • A better solution is to use something like SQLCipher which is a fully encrypted SQLite database. The encryption key can be enforced by the application and separate from the user's pin code.
Other security best practices are:
  • Only communicate with remote servers over SSL/HTTPS.
  • If possible implement certificate pinning in the application to prevent man-in-the-middle attacks on public WiFi.
  • Clear sensitive data out of memory by overwriting it.
  • Ensure all validation of data being submitted is also run on the server side.

Question 18

What is MVC? How is it implemented in iOS? What are some pitfalls you've experienced with it? Are there any alternatives to MVC?
MVC stands for Model, View, Controller. It is a design pattern that defines how to separate out logic when implementing user interfaces. In iOS, Apple provides UIView as a base class for allViews, UIViewController is provided to support the Controller which can listen to events in aView and update the View when data changes. The Model represents data in an application and can be implemented using any NSObject, including data collections like NSArray andNSDictionary.
Some of the pitfalls that people hit are bloated UIViewController and not separating out code into classes beyond the MVC format. I'd highly recommend reading up on some solutions to this:

Question 19

A product manager in your company reports that the application is crashing. What do you do?
This is a great question in any programming language and is really designed to see how you problem solve. You're not given much information, but some interviews will slip you more details of the issue as you go along. Start simple:
  • get the exact steps to reproduce it.
  • find out the device, iOS version.
  • do they have the latest version?
  • get device logs if possible.
Once you can reproduce it or have more information then start using tooling. Let's say it crashes because of a memory leak, I'd expect to see someone suggest using Instruments leak tool. A really impressive candidate would start talking about writing a unit test that reproduces the issue and debugging through it.
Other variations of this question include slow UI or the application freezing. Again the idea is to see how you problem solve, what tools do you know about that would help and do you know how to use them correctly.

Question 20

What is AutoLayout? What does it mean when a constraint is "broken" by iOS?
AutoLayout is way of laying out UIViews using a set of constraints that specify the location and size based relative to other views or based on explicit values. AutoLayout makes it easier to design screens that resize and layout out their components better based on the size and orientation of a screen. Constraints include:
  • setting the horizontal/vertical distance between 2 views
  • setting the height/width to be a ratio relative to a different view
  • a width/height/spacing can be an explicit static value
Sometimes constraints conflict with each other. For example imagine a UIView which has 2 height constraints: one says make the UIView 200px high, and the second says make the height twice the height of a button. If the iOS runtime can not satisfy both of these constraints then it has to pick only one. The other is then reported as being "broken" by iOS.

Labels: