90-What’s your preference when writing UI’s, Xib files, Storyboards or programmatic UIView?

There’s no right or wrong answer to this, but it’s great way of seeing if you understand the benefits and challenges with each approach. Here’s the common answers I hear:

• Storyboard’s and Xib’s are great for quickly producing UI’s that match a design spec. They are also really easy for product managers to visually see how far along a screen is.

• Storyboard’s are also great at representing a flow through an application and allowing a high-level visualisation of an entire application.

• Storyboard’s drawbacks are that in a team environment they are difficult to work on collaboratively because they’re a single file and merge’s become difficult to manage.

• Storyboards and Xib files can also suffer from duplication and become difficult to update. For example if all button’s need to look identical and suddenly need a colour change, then it can be a long/difficult process to do this across storyboards and xibs.

• Programmatically constructing UIView’s can be verbose and tedious, but it can allow for greater control and also easier separation and sharing of code. They can also be more easily unit tested.

Most developers will propose a combination of all 3 where it makes sense to share code, then re-usable UIViews or Xib files.

91-strong, weak, unsafe_unretained, autoreleasing, NSAutoReleasePool, release and drain?

drain: releases the NSAutoreleasePool itself it have number of objects.

In a reference-counted environment, drain does perform the same operations as release, so the two are in that sense equivalent. To emphasise, this means you do not leak a pool if you use drain rather than release.

In a garbage-collected environment, release is a no-op. Thus it has no effect. drain, on the other hand, contains a hint to the collector that it should “collect if needed”. Thus in a garbage-collected environment, using drain helps the system balance collection sweeps.

Autorelease: By sending an object an autorelease message, it is added to the local AutoReleasePool, and you no longer have to worry about it, because when the AutoReleasePool is destroyed (as happens in the course of event processing by the system) the object will receive a release message, its RetainCount will be decremented, and the GarbageCollection system will destroy the object if the RetainCount is zero.

Release: retain count is decremented at this point and frees a memory of object..

Autorelease pools: provide a mechanism whereby you can send an object a “deferred” release message. This is useful in situations where you want to relinquish ownership of an object, but want to avoid the possibility of it being deallocated immediately (such as when you return an object from a method).

Typically, you don’t need to create your own autorelease pools, but there are some situations in which either you must or it is beneficial to do so.

Every time -autorelease is sent to an object, it is added to the inner-most 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 too 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.

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.

Ball *ball = [[[[Ball alloc] init] autorelease] autorelease];

It will crash because it’s added twice to the autorelease pool and when it it dequeued the autorelease pool calls release more than once.

  1. If you are writing a program that is not based on a UI framework, such as a command-line tool.
  2. If you write a loop that creates many temporary objects.You may create an autorelease pool inside the loop to dispose of those objects before the next iteration. Using an autorelease pool in the loop helps to reduce the maximum memory footprint of the application.

3. If you spawn a secondary thread.

The strong and weak are new ARC types replacing retain and assign respectively.

Strong: reference is a reference to an object that stops it from being deallocated. In other words it creates an owner relationship, strong is the default so you don’t need to type it. This means any object created using alloc/init is retained for the lifetime of its current scope. The “current scope” usually means the braces in which the variable is declared.

Weak: reference is a reference to an object that does not stop it from being deallocated. In other words, it does not create an owner relationship.Delegates and outlets should be weak, weak means the object can be destroyed at anytime. This is only useful if the object is somehow strongly referenced somewhere else. When destroyed, a variable with weak is set to nil.

A weak reference allows the possibility of it to become nil (this happens automatically when the referenced object is deallocated), therefore the type of your property must be optional — so you, as a programmer, are obligated to check it before you use it (basically the compiler forces you, as much as it can, to write safe code).

unsafe_unretained/unowned weak: is just like weak but the pointer is not set to nil when the object is deallocated. Instead the pointer is left dangling.

An unowned reference presumes that it will never become nil during its lifetime. An unowned reference must be set during initialisation — this means that the reference will be defined as a non-optional type that can be used safely without checks. If somehow the object being referred to is deallocated, then the app will crash when the unowned reference will be used.

If self could be nil in the closure use [weak self].

If self will never be nil in the closure use [unowned self].

If it’s crashing when you use [unowned self] then self is probably nil at some point in that closure and you probably need to use [weak self] instead.

92-What is AutoLayout? What does it mean when a constraint is “broken” by iOS?

AutoLayout provides a flexible and powerful layout system that describes how views and the UI controls calculates the size and position in the hierarchy.AutoLayout is way of laying out UIViews using a set of constraints that specify the location and size based relative to other views or based on explicit values. AutoLayout makes it easier to design screens that resize and layout out their components better based on the size and orientation of a screen. _Constraint_s include:

• setting the horizontal/vertical distance between 2 views

• setting the height/width to be a ratio relative to a different view

• a width/height/spacing can be an explicit static value

Sometimes constraints conflict with each other. For example imagine a UIView which has 2 height constraints: one says make the UIView 200px high, and the second says make the height twice the height of a button. If the iOS runtime can not satisfy both of these constraints then it has to pick only one. The other is then reported as being “broken” by iOS.

93-A product manager in your company reports that the application is crashing. What do you do?

This is a great question in any programming language and is really designed to see how you problem solve. You’re not given much information, but some interviews will slip you more details of the issue as you go along. Start simple:

• get the exact steps to reproduce it.

• find out the device, iOS version.

• do they have the latest version?

• get device logs if possible.

Once you can reproduce it or have more information than start using tooling. Let’s say it crashes because of a memory leak, I’d expect to see someone suggest using Instruments leak tool. A really impressive candidate would start talking about writing a unit test that reproduces the issue and debugging through it.

Other variations of this question include slow UI or the application freezing. Again the idea is to see how you problem solve, what tools do you know about that would help and do you know how to use them correctly.

94-What makes React Native special for iOS?

Unlike PhoneGap)with React Native your application logic is written and runs in JavaScript, whereas your application UI is fully native; therefore you have none of the compromises typically associated with HTML5 UI.Additionally (unlike Titanium), React introduces a novel, radical and highly functional approach to constructing user interfaces. In brief, the application UI is simply expressed as a function of the current application state.

95-Consider the following code:

var defaults = NSUserDefaults.standardUserDefaults()

var userPref = defaults.stringForKey(“userPref”)!

printString(userPref)

func printString(string: String) {

println(string)

}

Where is the bug? What does this bug cause? What’s the proper way to fix it?

Answer: The second line uses the stringForKey method of NSUserDefaults, which returns an optional, to account for the key not being found, or for the corresponding value not being convertible to a string.

During its execution, if the key is found and the corresponding value is a string, the above code works correctly. But if the key doesn’t exist, or the corresponding value is not a string, the app crashes with the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

The reason is that the forced unwrapping operator ! is attempting to force unwrap a value from a nil optional. The forced unwrapping operator should be used only when an optional is known to contain a non-nil value.

The solution consists of making sure that the optional is not nil before force-unwrapping it:

let userPref = defaults.stringForKey(“userPref”)

if userPref != nil {

printString(userPref!)

}

An even better way is by using optional binding:

if let userPref = defaults.stringForKey(“userPref”) {

printString(userPref)

}

96-How should one handle errors in Swift?

In Swift, errors are thrown and handled inside of do-catch blocks.

The method for handling errors in Swift differ a bit from Objective-C. In Swift, it’s possible to declare that a function throws an error. It is, therefore, the caller’s responsibility to handle the error or propagate it. This is similar to how Java handles the situation.You simply declare that a function can throw an error by appending the throws keyword to the function name. Any function that calls such a method must call it from a try block.

func canThrowErrors() throws -> String

//How to call a method that throws an error

try canThrowErrors()

//Or specify it as an optional

let maybe = try? canThrowErrors()</pre>

97.Should I learn Swift or Objective-C and Differences Between Swift And Objective-C?

Swift: Apple has made it clear that Swift is the cornerstone of the future of iOS development. Plus, you can still utilise Objective-C files alongside Swift code, so you won’t miss out on any pre-existing libraries and code.Apple boasts that Swift is up to 2.6x faster than Objective-C and 8.4x faster than Python 2.7. And why should you care about how quickly code executes? Well, faster running code makes for more efficient and smoother running apps, which makes for a better experience for your user.

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.

Swift is probably most similar in look and feel to Ruby or Python. Though you’ll also probably recognise some C syntax.

1. Optionals

Optionals are a concept which doesn’t exist in C or Objective-C. They allow functions which may not always be able to return a meaningful value (e.g. in the event of invalid input) to return either a value encapsulated in an optional or nil. In C and Objective-C, we can already return nil from a function that would normally return an object, but we don’t have this option for functions which are expected to return a basic type such as int, float, or double.

2. Control Flow

Anyone who’s programmed in C or a C-like language is familiar with the use of curly braces ({}) to delimit code blocks. In Swift, however, they’re not just a good idea: they’re the law!

3. Type Inference

Swift introduces type safety to iOS development. Once a variable is declared with a particular type, its type is static and cannot be changed. The compiler is also smart enough to figure out (or infer) what type your variables should be based on the values you assign them.

4. Tuples

Swift supports tuples, values which store groups of other values. Unlike arrays, the values in a tuple don’t have to all be the same type.

5. String Manipulation

Swift offers huge improvements over Objective-C in terms of string manipulation. For starters, you don’t have to worry about mutable vs. immutable strings anymore: just declare your string with var if you want to change it in the future, or with let if you need it to remain constant.

6. Guard And Defer

We have guard, a new conditional statement which can make this code much more readable. Guard stops program flow if a condition is not met:

Using defer inside a method means that its work will be executed as the method is exiting. For example:

override func viewDidLoad() {

super.viewDidLoad()

print(“Step 1”)

myFunc()

print(“Step 5”)

}

func myFunc() {

print(“Step 2”)

defer { print(“Step 3”) }

print(“Step 4”)

}

That will print “Step 1”, “Step 2”, “Step 4”, “Step 3”, “Step 5” — steps 3 and 4 are switched because 3 is deferred until the myFunc() method ends, i.e. when it goes out of scope programmatically.

This scope is effectively anything in braces, { and }, but realistically there are two main ways you may want to use it: inside a do block and inside a loop.

7. Functional Programming Patterns

Swift incorporates a number of functional programming features, such as map and filter, which can be used on any collection which implements the CollectionType protocol:

8. Enumerations

In Swift, enumerations are more powerful than they ever were in Objective-C: they can now contain methods and be passed by value.

9. Functions

Swift’s function syntax is flexible enough to define anything from a simple C-style function to a complex Objective-C-style method with local and external parameter names.

Every function in Swift has a type, which consists of the function’s parameter types and return type. This means you can assign functions to variables or pass them as parameters to other functions:

10. Do Statement

The do statement in Swift allows you to introduce a new scope:

Do statements can also contain one or more catch clauses:

Difference between ‘C’ and ‘Swift’ language is that

Swift

• In a swift, the variable and constants are declared before their use

• You have to use “let” keyword for constant and “var” keyword for variable

• There is no need to end code with semi-colon

• Concatenating strings is easy in swift and allows to make a new string from a mix of constants, literals, variables, as well as expressions

• Swift does not require to create a separate interface like Objective C. You can define classes in a single file (.swift)

• Swift enables you to define methods in class, structure or enumeration

• In Swift, you use “ +=” Operator to add an item

Objective-C

• In objective C, you have to declare variable as NSString and constant as int

• In objective C, variable is declared as “ and constant as “

• The code ends with semi-colon

• In objective C, you have to choose between NSMutableString and NSString for string to be modified.

• For classes, you create separate interface (.h) and implementation (.m) files for classes

• Objective does not allow this

• In C, you use “addObject”: method of NSMutable array to append a new item to an array

98.Subclass, Category and Extensions in Objective C

Category: is a feature of the Objective-C language that enables you to add methods (interface and implementation) to a class without having to make a subclass. There is no runtime difference within the scope of your program between the original methods of the class and the methods added by the category. The methods in the category become part of the class type and are inherited by all the class’s subclasses.As with delegation, categories are not a strict adaptation of the Decorator pattern, fulfilling the intent but taking a different path to implementing that intent. The behaviour added by categories is a compile-time artefact, and is not something dynamically acquired. Moreover, categories do not encapsulate an instance of the class being extended.

You may implement categories in your code to extend classes without subclassing or to group related methods. However, you should be aware of these caveats:

  • You cannot add instance variables to the class.
  • If you override existing methods of the class, your application may behave

unpredictably.

Subclass in Objective C:

Subclassing in simple words is changing the behaviour of properties or methods of an existing class or in other words subclassing is inheriting a class and modifying the methods or properties of super class however you want.

Extensions in Objective C:

Extensions are similar to categories but the need of extension is different.

  • Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation of the class.
  • Extensions can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension).
  • Extensions will be local to a class file.

Class extensions are similar to categories. The main difference is that with an extension, the compiler will expect you to implement the methods within your main @implementation, whereas with a category you have a separate @implementation block. So you should pretty much only use an extension at the top of your main .m file (the only place you should care about ivars, incidentally) it’s meant to be just that, an extension.

Usually people will use extensions to hide private information off a class without exposing them to access from any other class.

99. What is an API

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message, or check the weather on your phone, you’re using an API.When you use an application on your mobile phone, the application connects to the Internet and sends data to a server. The server then retrieves that data, interprets it, performs the necessary actions and sends it back to your phone. The application then interprets that data and presents you with the information you wanted in a readable way. This is what an API is — all of this happens via API.

100.What is the biggest difference between NSURLConnection and NSURLSession?

NSURLConnection: if you suddenly realised you needed to do those things, you had to refactor your code to not use block-based callbacks.if we have an open connection with NSURLConnection and the system interrupt our App, when our App goes to background mode, everything we have received or sent were lost.

Methods used in NSURLConnection:

(1)Connection did receive Response (2)Connection did receive Data

(3)Connection fail with error (4)Connection did finish loading.

NSURLSession: is designed around the assumption that you’ll have a lot of requests that need similar configuration (standard sets of headers, etc.), and makes life much easier if you do.NSURLSession also provides support for background downloads, which make it possible to continue downloading resources while your app isn’t running (or when it is in the background on iOS). For some use cases, this is also a major win.NSURLSession also provides grouping of related requests, making it easy to cancel all of the requests associated with a particular work unit, such as canceling all loads associated with loading a web page when the user closes the window or tab.NSURLSession also provides nicer interfaces for requesting data using blocks, in that it allows you to combine them with delegate methods for doing custom authentication handling, redirect handling, etc.

In an application we usually works with

1 Data tasks — Data tasks are used for requesting data from a server, such as JSON data. These data are usually stored in memory and never touches the File System We can use NSURLSessionDataTask.

2 Upload Tasks — Upload tasks are used to upload data to a remote destination. We can use NSURLSessionUploadTask.

3 Download Tasks — Downloading a file and Storing in a temporary location. We can use NSURLSessionDownloadTask.

--

--

Sandeep Reddy Challa

I have around 14 years of experience in iOS development and lead/senior developer