https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/MobileDeviceManagementProtocolRef/1-Introduction/Introduction.html
Wednesday, 25 January 2017
Friday, 20 January 2017
Swift interview Questions 2017
1) Explain what is Swift Programming Language?
Swift is a programming language and system for creating applications for iOS and OS X. It is an innovative programming language for Cocoa and Cocoa Touch.
2) Explain how you define variables in Swift language?
Variables and constants must be declared before they are used. You announce constants with the let keyword and variables with the var keyword. Both variables and dictionaries are described using brackets. For example,
Var Guru99 = “This is Guru99”
Let ksomeconstant = 30
3) Explain how Swift program is deployed?
Swift program deploys the application in a Tomcat installation by default. The deploy script bundles the client code into JavaScript, gathers all the server side classes required and packages them into file Hello.war. This file together with a GWT jar and a Swift runtime jar is copied into the Tomcat installation. If CATALINA_HOME is not set, these files require to be copied manually.
4) Mention what are the features of Swift Programming?
- It eliminates entire classes of unsafe code
- Variables are always initialized before use
- Arrays and integers are checked for overflow
- Memory is managed automatically
- Instead of using “if” statement in conditional programming, swift has “switch” function
5) Mention what is the difference between Swift and ‘Objective-C’ language?
Difference between ‘C’ and ‘Swift’ language is that
| Swift | Objective-C |
|
|
6) Mention what are the type of integers does Swift have?
Swift provides unsigned and signed integers in 8, 16, 32 and 64 bit forms. Similar to C these integers follow a naming convention. For instance, unsigned integer is denoted by type UInt8 while 32 bit signed integer will be denoted by type Int32.
7) Mention what is the Floating point numbers and what are the types of floating number in Swift?
Floating numbers are numbers with a fractional component, like 3.25169 and -238.21. Floating point types can represent a wider range of values than integer types. There are two signed floating point number
- Double: It represents a 64 bit floating point number, it is used when floating point values must be very large
- Float: It represents a 32 bit floating point number, it is used when floating point values does not need 64 bit precision
8) Explain how multiple line comment can be written in swift?
Multiple line comment can be written as forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/).
9) What is de-initializer and how it is written in Swift?
A de-initializer is declared immediately before a class instance is de-allocated. You write de-initializer with the deinit keyword. De-initializer is written without any parenthesis, and it does not take any parameters. It is written as
deinit {
// perform the deinitialization
}
10) Mention what are the collection types available in Swift?
In Swift, collection types come in two varieties Array and Dictionary
- Array: You can create an Array of a single type or an array with multiple types. Swift usually prefers the former one
Example for single type array is,
Var cardName : [String] = [ “Robert” , “Lisa” , “Kevin”]
// Swift can infer [String] so we can also write it as:
Var cardNames = [ “Robert”, “Lisa”, “Kevin”] // inferred as [String]
To add an array you need to use the subscript println(CardNames[0])
- Dictionary: It is similar to a Hash table as in other programming language. A dictionary enables you to store key-value pairs and access the value by providing the key
var cards = [ “Robert”: 22, “Lisa” : 24, and “Kevin”: 26]
11) List out what are the control transfer statements used in Swift?
Control transfer statements used in Swift includes
- Continue
- Break
- Fallthrough
- Return
12) Explain what is optional chaining?
Optional chaining is a process of querying and calling properties. Multiple queries can be chained together, and if any link in the chain is nil then, the entire chain fails.
13) How base-class is defined in Swift?
In Swift the classes are not inherited from the base class and the classes that you define without specifying its superclass, automatically becomes the base-class.
14) Explain what Lazy stored properties is and when it is useful?
Lazy stored properties are used for a property whose initial values is not calculated until the first time it is used. You can declare a lazy stored property by writing the lazy modifier before its declaration. Lazy properties are useful when the initial value for a property is reliant on outside factors whose values are unknown.
15) Mention what is the characteristics of Switch in Swift?
- It supports any kind of data, and not only synchronize but also checks for equality
- When a case is matched in switch, the program exists from the switch case and does not continue checking next cases. So you don’t need to explicitly break out the switch at the end of case
- Switch statement must be exhaustive, which means that you have to cover all possible values for your variable
- There is no fallthrough in switch statements and therefore break is not required
8. How to make an API (Web service) Call?
To make API (Web Service ) call in Swift you can do,
var params = [“MIN”:”f8d16d98ad12acdbbe1de647414495ec”, “MobileType”:”IOS”,”format”:”json”,”OperatorID”:”500200000000010025″] as Dictionary // Its the parameters required in the webservice.
var request = NSMutableURLRequest(URL: NSURL(string: kDataURL)) // Here kDataURL is the marco for URL.
var session = NSURLSession.sharedSession()
request.HTTPMethod = “POST”
var session = NSURLSession.sharedSession()
request.HTTPMethod = “POST”
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue(“application/json”, forHTTPHeaderField: “Content-Type”)
request.addValue(“application/json”, forHTTPHeaderField: “Accept”)
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue(“application/json”, forHTTPHeaderField: “Content-Type”)
request.addValue(“application/json”, forHTTPHeaderField: “Accept”)
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// println(“Response: \(response)”)
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println(“Body: \(strData)”)
// println(“Response: \(response)”)
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println(“Body: \(strData)”)
var err: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary
println(“json1\(json2)”)
1. Why is the language called Swift?
We could make the obvious popular culture joke, but in all seriousness, the language was designed with two goals in mind:
- swift to code
- swift to execute
In terms of speed, Swift uses the LLVM compiler, and compiles Swift code to optimized native code depending on target device. In terms of learning curve, the Swift syntax was designed to be clean and easy to read.
2. Should I learn Swift or Objective-C?
Whether you should learn Swift or Objective-C was the basis of a discussion back in September, and the answer has not changed – Swift! Apple has made it clear that Swift is the cornerstone of the future of iOS development. Plus, you can still utilize Objective-C files alongside Swift code, so you won’t miss out on any pre-existing libraries and code.
3. How easy is Swift to learn?
Swift was designed to be friendly for new programmers, and as a result it is incredibly easy to learn. According to Apple, Swift is the “first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language.” Some have even called Swift the new BASIC.
5. Why did Apple decide to create a new language?
Objective-C has been Apple’s primary programming language for app writing since OS X was created. In that time, programming languages and practices changed drastically, especially in mobile development. Rather than adopt a new, already existing language, Apple created a new language tailored specifically for development on their own hardware.
6. Can I create an app in Swift and submit it to the app store?
Absolutely! In fact, you were able to as soon as Xcode 6 and iOS 8 launched.
7. Why was there a need to go from Objective-C to Swift?
As mention in the answer to question five, after 20 years, Objective-C was starting to show its age. Plus, Objective-C is a difficult language for new programmers to learn, so the barrier to entry is pretty high. Swift provides a modern language tailor-made for Apple hardware.
8. How stable is Swift?
As with any new language, there is a potential for bugs. While you may encounter some trouble with the Swift language, the majority of issues were addressed before the 1.0 release.
The thing to most look out for is changes to the Swift language during each update. For example, when updating from 1.0 to 1.1, Apple introduced a new feature: failable initializers. You can expect that the language will change as more people use it and give feedback to Apple. Stay apprised of changes using the revision history for The Swift Programming Language.
9. What other languages is it similar to?
Swift is probably most similar in look and feel to Ruby or Python. Though you’ll also probably recognize some C syntax.
10. Is it compatible with iOS 6 & 7?
Swift can be run on iOS 7, but not iOS 6
Difference between categories and extensions?
| ||||||||
Thursday, 19 January 2017
iOS Interview Questions 2017

*Q: How would you create your own custom view?A:By Subclassing the UIView class.
*Q: What is App Bundle?
A:When you build your iOS app, Xcode packages it as a bundle. A bundle is a directory in the file system that groups related resources together in one place. An iOS app bundle contains the app executable file and supporting resource files such as app icons, image files, and localized content.
*Q: Whats fast enumeration?
A:Fast enumeration is a language feature that allows you to enumerate over the contents of a collection. (Your code will also run faster because the internal implementation reduces message send overhead and increases pipelining potential.)
*Q: Whats a struct?
A:A struct is a special C data type that encapsulates other pieces of data into a single cohesive unit. Like an object, but built into C.
*Q: Whats the difference between NSArray and NSMutableArray?
A:NSArrayʼs contents can not be modified once itʼs been created whereas a NSMutableArray can be modified as needed, i.e items can be added/removed from it.
*Q: Explain retain counts.
A:Retain counts are the way in which memory is managed in Objective-C. When you create an object, it has a retain count of 1. When you send an object a retain message, its retain count is incremented by 1. When you send an object a release message, its retain count is decremented by 1. When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future. If an objectʼs retain count is reduced to 0, it is deallocated.
*Q: Whats the difference between frame and bounds?
A:The frame of a view is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within. The bounds of a view is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).
*Q: Is a delegate retained?
A:No, the delegate is never retained! Ever!
*Q:Outline the class hierarchy for a UIButton until NSObject.
A:UIButton inherits from UIControl, UIControl inherits from UIView, UIView inherits from UIResponder, UIResponder inherits from the root class NSObject.*Q:What are the App states. Explain them?
A:- Not running State: The app has not been launched or was running but was terminated by the system.
- Inactive state: 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. The only time it stays inactive for any period of time is when the user locks the screen or the system prompts the user to respond to some event, such as an incoming phone call or SMS message.
- Active state: The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.
- Background state: The app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state. For information about how to execute code while in the background, see “Background Execution and Multitasking.”
- Suspended state:The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code. When a low-memory condition occurs, the system may purge suspended apps without notice to make more space for the foreground app.
*Q: Explain how the push notification works.
A:
*Q: Explain the steps involved in submitting the App to App-Store.
A:
Apple provides the tools you need to develop, test, and submit your iOS app to the App Store. To run an app on a device, the device needs to be provisioned for development, and later provisioned for testing. You also need to provide information about your app that the App Store displays to customers and upload screenshots. Then you submit the app to Apple for approval. After the app is approved, you set a date the app should appear in the App Store as well as its price. Finally, you use Apple’s tools to monitor the sales of the app, customer reviews, and crash reports. Then you repeat the entire process again to submit updates to your app.
*Q: Why do we need to use @Synthesize?
A:
We can use generated code like nonatomic, atmoic, retain without writing any lines of code. We also have getter and setter methods. To use this, you have 2 other ways: @synthesize or @dynamic: @synthesize, compiler will generate the getter and setter automatically for you, @dynamic: you have to write them yourself.@property is really good for memory management, for example: retain.How can you do retain without @property?
if (_variable != object){ [_variable release]; _variable = nil; _variable = [object retain]; }How can you use it with @property?self.variable = object; When we are calling the above line, we actually call the setter like [self setVariable:object] and then the generated setter will do its job.
*Q: Multitasking support is available from which version?
A:
iOS 4.0.
*Q: How many bytes we can send to apple push notification server?
A:
256bytes.
*Q: Can you just explain about memory management in iOS?
A:
Refer: iOS Memory Management
*Q: What is code signing?
A:
Signing an application allows the system to identify who signed the application and to verify that the application has not been modified since it was signed. Signing is a requirement for submitting to the App Store (both for iOS and Mac apps). OS X and iOS verify the signature of applications downloaded from the App Store to ensure that they they do not run applications with invalid signatures. This lets users trust that the application was signed by an Apple source and hasn’t been modified since it was signed.
Xcode uses your digital identity to sign your application during the build process. This digital identity consists of a public-private key pair and a certificate. The private key is used by cryptographic functions to generate the signature. The certificate is issued by Apple; it contains the public key and identifies you as the owner of the key pair.
In order to sign applications, you must have both parts of your digital identity installed. Use Xcode or Keychain Access to manage your digital identities. Depending on your role in your development team, you may have multiple digital identities for use in different contexts. For example, the identity you use for signing during development is different from the identity you user for distribution on the App Store. Different digital identities are also used for development on OS X and on iOS.
An application’s executable code is protected by its signature because the signature becomes invalid if any of the executable code in the application bundle changes. Resources such as images and nib files are not signed; a change to these files does not invalidate the signature.
An application’s signature can be removed, and the application can be re-signed using another digital identity. For example, Apple re-signs all applications sold on the App Store. Also, a fully-tested development build of your application can be re-signed for submission to the App Store. Thus the signature is best understood not as indelible proof of the application’s origins but as a verifiable mark placed by the signer

This is continuation post for iOS Interview Questions for fresher‘s.list of iOS interview questions helped you to clear iOS/iPhone interviews
*Q: Explain the options and bars available in xcode 4.x workspace window ?
A: [block]1[/block]
*Q: If I call performSelector:withObject:afterDelay: – is the object retained?
A:
Yes, the object is retained. It creates a timer that calls a selector on the current threads run loop. It may not be 100% precise time-wise as it attempts to dequeue the message from
the run loop and perform the selector.
the run loop and perform the selector.
*Q: Can you explain what happens when you call autorelease on an object?
A:
When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future. The object is added to an autorelease pool on the current thread. The main thread loop creates an autorelease pool at the beginning of the function, and release it at the end. This establishes a pool for the lifetime of the task. However, this also means that any autoreleased objects created during the lifetime of the task are not disposed of until the task completes. This may lead to the taskʼs memory footprint increasing unnecessarily. You can also consider creating pools with a narrower scope or use NSOperationQueue with itʼs own autorelease pool. (Also important – You only release or autorelease objects you own.)
*Q: Whats the NSCoder class used for?
A:
NSCoder is an abstractClass which represents a stream of data. They are used in Archiving and Unarchiving objects. NSCoder objects are usually used in a method that is being implemented so that the class conforms to the protocol. (which has something like encodeObject and decodeObject methods in them).
*Q: Whats an NSOperationQueue and how/would you use it?
A:
The NSOperationQueue class regulates the execution of a set of NSOperation objects. An operation queue is generally used to perform some asynchronous operations on a background thread so as not to block the main thread.
*Q: Explain the correct way to manage Outlets memory.
A:
Create them as properties in the header that are retained. In the viewDidUnload set the outlets to nil(i.e self.outlet = nil). Finally in dealloc make sure to release the outlet.
iOS interview Questions for Expert level
*Q:What is sandbox?
A:
For security reasons, iOS places each app (including its preferences and data) in a sandbox at install time. A sandbox is a set of fine-grained controls that limit the app’s access to files, preferences, network resources, hardware, and so on. As part of the sandboxing process, the system installs each app in its own sandbox directory, which acts as the home for the app and its data.

To help apps organize their data, each sandbox directory contains several well-known subdirectories for placing files. Above Figure shows the basic layout of a sandbox directory.
*Q:Is the delegate for a CAAnimation retained?
A:
Yes it is!! This is one of the rare exceptions to memory management rules.
*Q: What is dynamic?
A:You use the@dynamickeyword to tell the compiler that you will fulfill the API contract implied by a property either by providing method implementations directly or at runtime using other mechanisms such as dynamic loading of code or dynamic method resolution. It suppresses the warnings that the compiler would otherwise generate if it can’t find suitable implementations. You should use it only if you know that the methods will be available at runtime.
*Q: What happens when the following code executes?
Ball *ball = [[[[Ball alloc] init] autorelease] autorelease];
A:
It will crash because itʼs added twice to the autorelease pool and when it it dequeued the autorelease pool calls release more than once.
*Q: Explain the difference between NSOperationQueue concurrent and non-concurrent.
A:
In the context of an NSOperation object, which runs in an NSOperationQueue, the terms concurrent and non-concurrent do not necessarily refer to the side-by-side execution of threads. Instead, a non-concurrent operation is one that executes using the environment that is provided for it while a concurrent operation is responsible for setting up its own execution environment.
*Q: Implement your own synthesized methods for the property NSString *title.
A:
Well you would want to implement the getter and setter for the title object. Something like this: view source print?
– (NSString*) title // Getter method
{
return title;
}
– (void) setTitle: (NSString*) newTitle //Setter method
{
if (newTitle != title)
{
[title release];
title = [newTitle retain]; // Or copy, depending on your needs.
}
}
*Q: Implement the following methods: retain, release, autorelease.
A:
-(id)retain
{
NSIncrementExtraRefCount(self);
return self;
}
-(void)release
{
if(NSDecrementExtraRefCountWasZero(self))
{NSDeallocateObject(self);
}
}
-(id)autorelease
{ // Add the object to the autorelease pool
[NSAutoreleasePool addObject:self];
return self;
}
*Q: What are all the newly added frameworks iOS 4.3 to iOS 5.0?
A:- Accounts
- CoreBluetooth
- CoreImage
- GLKit
- GSS
- NewsstandKit
*Q: What is Automatic Reference Counting (ARC) ?
A:
ARC is a compiler-level feature that simplifies the process of managing the lifetimes of Objective-C objects. Instead of you having to remember when to retain or release an object, ARC evaluates the lifetime requirements of your objects and automatically inserts the appropriate method calls at compile time.
*Q: What is the difference between retain & assign?
A:
Assign creates a reference from one object to another without increasing the source’s retain count.
if (_variable != object){ [_variable release]; _variable = nil; _variable = object; }Retain creates a reference from one object to another and increases the retain count of the source object.if (_variable != object){ [_variable release]; _variable = nil; _variable = [object retain]; }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.
Want to ace your technical interview? Schedule a Technical Interview Practice Session with an expert now!
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 the
UIImage 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 loadView. viewDidAppear 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. when
cellForRowAtIndexPathis 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?
NSThreadcreates a new low-level thread which can be started by calling thestartmethod.
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(myThreadMainMethod:)
object:nil];
[myThread start];
NSOperationQueueallows a pool of threads to be created and used to executeNSOperations in parallel.NSOperations can also be run on the main thread by askingNSOperationQueuefor themainQueue.
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 associated UIViewControllers, if none of those handle the event then the UIWindow is asked if it can handle it and finally if that doesn't handle the event then the UIApplicationDelegate is asked.
If you get the opportunity to draw this one out, it's worth doing to impress the interviewer:
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 _delegate_s 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 programmatic
UIView?
There's no right or wrong answer to this, but it's great way of seeing if you understand the benefits and challenges with each approach. Here's the common answers I hear:
- Storyboard's and Xib's are great for quickly producing UI's that match a design spec. They are also really easy for product managers to visually see how far along a screen is.
- Storyboard's are also great at representing a flow through an application and allowing a high-level 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 all _View_s, UIViewController is provided to support the Controller which can listen to events in a View 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 and NSDictionary.
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:- https://www.objc.io/issues/1-view-controllers/lighter-view-controllers/
- https://speakerdeck.com/trianglecocoa/unburdened-viewcontrollers-by-jay-thrash
- https://programmers.stackexchange.com/questions/177668/how-to-avoid-big-and-clumsy-uitableviewcontroller-on-ios
In terms of alternatives, this is pretty open ended. The most common alternative is MVVM using ReactiveCocoa, but others include VIPER and using Functional Reactive code.
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. _Constraint_s include:- setting the horizontal/vertical distance between 2 views
- setting the height/width to be a ratio relative to a different view
- a width/height/spacing can be an explicit static value
Sometimes constraints conflict with each other. For example imagine a
UIView which has 2 height constraints: one says make the UIView 200px high, and the second says make the height twice the height of a button. If the iOS runtime can not satisfy both of these constraints then it has to pick only one. The other is then reported as being "broken" by iOS.Q1. Where can you test Apple iPhone apps if you don’t have the device?
A. iOS Simulator can be used to test mobile applications. Xcode tool that comes along with iOS SDK includes Xcode IDE as well as the iOS Simulator. Xcode also includes all required tools and frameworks for building iOS apps. However, it is strongly recommended to test the app on the real device before publishing it.
Q2. Does iOS support multitasking? A. iOS 4 and above supports multi-tasking and allows apps to remain in the background until they are launched again or until they are terminated.
Q3. Which JSON framework is supported by iOS? A. SBJson framework is supported by iOS. It is a JSON parser and generator for Objective-C. SBJson provides flexible APIs and additional control that makes JSON handling easier.
Q4. What are the tools required to develop iOS applications? A. iOS development requires Intel-based Macintosh computer and iOS SDK.
Q5. Name the framework that is used to construct application’s user interface for iOS. A. The UIKit framework is used to develop application’s user interface for iOS. UIKit framework provides event handling, drawing model, windows, views, and controls specifically designed for a touch screen interface.
Q6. Name the application thread from where UIKit classes should be used? A. UIKit classes should be used only from an application’s main thread. Note: The derived classes of UIResponder and the classes which manipulate application’s user interface should be used from application’s main thread.
Q7. Which API is used to write test scripts that help in exercising the application's user interface elements? A. UI Automation API is used to automate test procedures. Tests scripts are written in JavaScript to the UI Automation API. This in turn simulates user interaction with the application and returns log information to the host computer.
App States and Multitasking
Q8. Why an app on iOS device behaves differently when running in foreground than in background? A. An application behaves differently when running in foreground than in background because of the limitation of resources on iOS devices.
Q9. How can an operating system improve battery life while running an app? A. An app is notified whenever the operating system moves the apps between foreground and background. The operating system improves battery life while it bounds what your app can do in the background. This also improves the user experience with foreground app.
Q10. Which framework delivers event to custom object when app is in foreground? A. The UIKit infrastructure takes care of delivering events to custom objects. As an app developer, you have to override methods in the appropriate objects to process those events.
App States
Q11. When an app is said to be in not running state? A. An app is said to be in 'not running' state when:
- it is not launched.
- it gets terminated by the system during running.
- it is not launched.
- it gets terminated by the system during running.
Q12. Assume that your app is running in the foreground but is currently not receiving events. In which sate it would be in? A. An app will be in InActive state if it is running in the foreground but is currently not receiving events. An app stays in InActive state only briefly as it transitions to a different state.
Q13. Give example scenarios when an application goes into InActive state? A. An app can get into InActive state when the user locks the screen or the system prompts the user to respond to some event e.g. SMS message, incoming call etc.
Q14. When an app is said to be in active state? A. An app is said to be in active state when it is running in foreground and is receiving events.
Q15. Name the app sate which it reaches briefly on its way to being suspended. A. An app enters background state briefly on its way to being suspended.
Q16. Assume that an app is not in foreground but is still executing code. In which state will it be in? A. Background state.
Q17. An app is loaded into memory but is not executing any code. In which state will it be in? A. An app is said to be in suspended state when it is still in memory but is not executing any code.
Q18. Assume that system is running low on memory. What can system do for suspended apps? A. In case system is running low on memory, the system may purge suspended apps without notice.
Q19. How can you respond to state transitions on your app? A. On state transitions can be responded to state changes in an appropriate way by calling corresponding methods on app's delegate object.
For example: applicationDidBecomeActive method can be used to prepare to run as the foreground app.
applicationDidEnterBackground method can be used to execute some code when app is running in the background and may be suspended at any time.
applicationWillEnterForeground method can be used to execute some code when your app is moving out of the background
applicationWillTerminate method is called when your app is being terminated.
applicationDidEnterBackground method can be used to execute some code when app is running in the background and may be suspended at any time.
applicationWillEnterForeground method can be used to execute some code when your app is moving out of the background
applicationWillTerminate method is called when your app is being terminated.
Q20. List down app's state transitions when it gets launched. A. Before the launch of an app, it is said to be in not running state.
When an app is launched, it moves to the active or background state, after transitioning briefly through the inactive state.
When an app is launched, it moves to the active or background state, after transitioning briefly through the inactive state.
Q21. Who calls the main function of you app during the app launch cycle? A. During app launching, the system creates a main thread for the app and calls the app’s main function on that main thread. The Xcode project's default main function hands over control to the UIKit framework, which takes care of initializing the app before it is run.
Core App Objects
Q22. What is the use of controller object UIApplication?
A. Controller object UIApplication is used without subclassing to manage the application event loop.
It coordinates other high-level app behaviors.
It works along with the app delegate object which contains app-level logic.
A. Controller object UIApplication is used without subclassing to manage the application event loop.
It coordinates other high-level app behaviors.
It works along with the app delegate object which contains app-level logic.
Q23. Which object is create by UIApplicationMain function at app launch time?
A. The app delegate object is created by UIApplicationMain function at app launch time. The app delegate object's main job is to handle state transitions within the app.
A. The app delegate object is created by UIApplicationMain function at app launch time. The app delegate object's main job is to handle state transitions within the app.
Q24. How is the app delegate is declared by Xcode project templates?
A. App delegate is declared as a subclass of UIResponder by Xcode project templates.
A. App delegate is declared as a subclass of UIResponder by Xcode project templates.
Q25. What happens if IApplication object does not handle an event?
A. In such case the event will be dispatched to your app delegate for processing.
A. In such case the event will be dispatched to your app delegate for processing.
Q26. Which app specific objects store the app's content?
A. Data model objects are app specific objects and store app’s content. Apps can also use document objects to manage some or all of their data model objects.
A. Data model objects are app specific objects and store app’s content. Apps can also use document objects to manage some or all of their data model objects.
Q27. Are document objects required for an application? What does they offer?
A. Document objects are not required but are very useful in grouping data that belongs in a single file or file package.
A. Document objects are not required but are very useful in grouping data that belongs in a single file or file package.
Q28. Which object manage the presentation of app's content on the screen?
A. View controller objects takes care of the presentation of app's content on the screen. A view controller is used to manage a single view along with the collection of subviews. It makes its views visible by installing them in the app’s window.
A. View controller objects takes care of the presentation of app's content on the screen. A view controller is used to manage a single view along with the collection of subviews. It makes its views visible by installing them in the app’s window.
Q29. Which is the super class of all view controller objects?
A. UIViewController class. The functionality for loading views, presenting them, rotating them in response to device rotations, and several other standard system behaviors are provided by UIViewController class.
A. UIViewController class. The functionality for loading views, presenting them, rotating them in response to device rotations, and several other standard system behaviors are provided by UIViewController class.
Q30. What is the purpose of UIWindow object?
A. The presentation of one or more views on a screen is coordinated by UIWindow object.
A. The presentation of one or more views on a screen is coordinated by UIWindow object.
Q31. How do you change the content of your app in order to change the views displayed in the corresponding window?
A. To change the content of your app, you use a view controller to change the views displayed in the corresponding window. Remember, window itself is never replaced.
A. To change the content of your app, you use a view controller to change the views displayed in the corresponding window. Remember, window itself is never replaced.
Q32. Define view object.
A. Views along with controls are used to provide visual representation of the app content. View is an object that draws content in a designated rectangular area and it responds to events within that area.
A. Views along with controls are used to provide visual representation of the app content. View is an object that draws content in a designated rectangular area and it responds to events within that area.
Q33. You wish to define your custom view. Which class will be subclassed?
A. Custom views can be defined by subclassing UIView.
A. Custom views can be defined by subclassing UIView.
Q34. Apart from incorporating views and controls, what else an app can incorporate?
A. Apart from incorporating views and controls, an app can also incorporate Core Animation layers into its view and control hierarchies.
A. Apart from incorporating views and controls, an app can also incorporate Core Animation layers into its view and control hierarchies.
Q35. What are layer objects and what do they represent?
A. Layer objects are data objects which represent visual content. Layer objects are used by views to render their content. Custom layer objects can also be added to the interface to implement complex animations and other types of sophisticated visual effects.
A. Layer objects are data objects which represent visual content. Layer objects are used by views to render their content. Custom layer objects can also be added to the interface to implement complex animations and other types of sophisticated visual effects.
What are different ways that you can specify the layout of elements in a
UIView?
Here are a few common ways to specify the layout of elements in a
UIView:- Using InterfaceBuilder, you can add a
XIBfile to your project, layout elements within it, and then load theXIBin your application code (either automatically, based on naming conventions, or manually). Also, using InterfaceBuilder you can create astoryboardfor your application. - You can your own code to use
NSLayoutConstraintsto have elements in a view arranged by Auto Layout. - You can create
CGRects describing the exact coordinates for each element and pass them toUIView’s- (id)initWithFrame:(CGRect)framemethod.
What’s the difference between an “app ID” and a “bundle ID” and what is each used for?
An App ID is a two-part string used to identify one or more apps from a single development team. The string consists of a Team ID and a bundle ID search string, with a period (.) separating the two parts. The Team ID is supplied by Apple and is unique to a specific development team, while the bundle ID search string is supplied by teh developer to match either the bundle ID of a single app or a set of bundle IDs for a group of apps.
Because most people think of the App ID as a string, they think it is interchangeable with Bundle ID. It appears this way because once the App ID is created in the Member Center, you only ever use the App ID Prefix which matches the Bundle ID of the Application Bundle.
The bundle ID uniquely defines each App. It is specified in Xcode. A single Xcode project can have multiple Targets and therefore output multiple apps. A common use case for this is an app that has both lite/free and pro/full versions or is branded multiple ways.
Subscribe to:
Comments (Atom)
Setting Up Multiple App Targets in Xcode from a Single Codebase
To create two different apps (like "Light" and "Regular") from the same codebase in Xcode, you can follow these steps b...
-
if u want to open in same window - ( WKWebView *) webView :( WKWebView *) webView createWebViewWithConfiguration :( WKWebViewConfigurat...
-
To create two different apps (like "Light" and "Regular") from the same codebase in Xcode, you can follow these steps b...
-
[[UIApplication sharedApplication] openURL: [NSURL URLWithString:@"prefs:root=General&path=Network"]]; List of curre...
