Search Your Question

Showing posts with label Intelegain Technology. Show all posts
Showing posts with label Intelegain Technology. Show all posts

What is MVVM?

MVVM - Model View ViewModel

Advantage : 

Better Separation of Concerns
In a project built with the Model-View-Controller pattern, you are often faced with the question which code goes where. Code that doesn’t fit or belong in the model or view layer is often put in the controller layer. This inevitably leads to fat controllers that are difficult to test and manage.

The MVVM pattern presents a better separation of concerns by adding view models to the mix. The view model translates the data of the model layer into something the view layer can use. The controller is no longer responsible for this task.

Improved Testability
View controllers are notoriously hard to test because of their relation to the view layer. By migrating data manipulation to the view model, testing becomes much easier. Testing view models is easy. Because a view model doesn’t have a reference to the object it is owned by, it easy to write unit tests for a view model.

Another, and often overlooked, benefit of MVVM is improved testability of view controllers. The view controller no longer depends on the model layer, which makes them easier to test.

Transparent Communication
The responsibilities of the view controller are reduced to controlling the interaction between the view layer and the model layer, glueing both layers together.

The view model provides a transparent interface to the view controller, which it uses to populate the view layer and interact with the model layer. This results in a transparent communication between the four layers of your application.

There are some rules you know when using MVVM

Rule1 : The view does not know about the controller it is owned by. Remember that views are supposed to be dumb. They only know how to present the data they are given to the user.
Rule 2 : The controller does not know about the model. This is what separates MVC from MVVM.
Rule 3 : The model does not know about the view model it is owned by.
Rule 4 : The view model owns the model. When using the Model-View-Controller pattern, the model is usually owned by the controller.
Rule 5 : The view controller owns the view. This relationship remains unchanged when using the Model-View-ViewModel pattern.
Rule 6 : And, finally, the controller owns the view model. It interacts with the model layer through one or more view models.

Meaning of ??, !!, !?, ?!

Ans : 

1. ?? is  Nil-Coalescing Operator. It is used to provide default value if value is nil.

let val = values["value1"] as? String ?? "default"

2. !!

i.e
struct StockFullData: Codable
{  
           var ok : Bool?  
           var sn : StockName?
}

struct StockName : Codable
{  
           let display_name : String?
}

Now Check :

print(s.sn?.display_name)      
print((s.sn?.display_name!))      
print((s.sn?.display_name!)!)      
 print((s.sn!.display_name!))

Output :

Optional("m")
Optional("m")
m
m

-> See third print, where we have used !! for extract value. I am not sure it is correct answer because it is like !)! .

3. !? : am finding answer or We can make custom operator using this .
4. ?! : am finding answer or We can make custom operator using this .

If you have any comment, question, or recommendation, feel free to post them in the comment section below!


CollectionViewDelegate and CollectionViewDataSource Methods

Ans :
Popular methods is designed by blue color.

CollectionViewDelegate Methods

Managing the Selected Cells
func collectionView(UICollectionView, shouldSelectItemAt: IndexPath) -> Bool
Asks the delegate if the specified item should be selected.

func collectionView(UICollectionView, didSelectItemAt: IndexPath)
Tells the delegate that the item at the specified index path was selected.

func collectionView(UICollectionView, shouldDeselectItemAt: IndexPath) -> Bool
Asks the delegate if the specified item should be deselected.

func collectionView(UICollectionView, didDeselectItemAt: IndexPath)
Tells the delegate that the item at the specified path was deselected.

Managing Cell Highlighting
func collectionView(UICollectionView, shouldHighlightItemAt: IndexPath) -> Bool
Asks the delegate if the item should be highlighted during tracking.

func collectionView(UICollectionView, didHighlightItemAt: IndexPath)
Tells the delegate that the item at the specified index path was highlighted.

func collectionView(UICollectionView, didUnhighlightItemAt: IndexPath)
Tells the delegate that the highlight was removed from the item at the specified index path.

Tracking the Addition and Removal of Views
func collectionView(UICollectionView, willDisplay: UICollectionViewCell, forItemAt: IndexPath)
Tells the delegate that the specified cell is about to be displayed in the collection view.

func collectionView(UICollectionView, willDisplaySupplementaryView: UICollectionReusableView, forElementKind: String, at: IndexPath)
Tells the delegate that the specified supplementary view is about to be displayed in the collection view.

func collectionView(UICollectionView, didEndDisplaying: UICollectionViewCell, forItemAt: IndexPath)
Tells the delegate that the specified cell was removed from the collection view.

func collectionView(UICollectionView, didEndDisplayingSupplementaryView: UICollectionReusableView, forElementOfKind: String, at: IndexPath)
Tells the delegate that the specified supplementary view was removed from the collection view.


Handling Layout Changes
func collectionView(UICollectionView, transitionLayoutForOldLayout: UICollectionViewLayout, newLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout
Asks for the custom transition layout to use when moving between the specified layouts.

func collectionView(UICollectionView, targetContentOffsetForProposedContentOffset: CGPoint) -> CGPoint
Gives the delegate an opportunity to customize the content offset for layout changes and animated updates.

func collectionView(UICollectionView, targetIndexPathForMoveFromItemAt: IndexPath, toProposedIndexPath: IndexPath) -> IndexPath
Asks the delegate for the index path to use when moving an item.

Managing Actions for Cells
func collectionView(UICollectionView, shouldShowMenuForItemAt: IndexPath) -> Bool
Asks the delegate if an action menu should be displayed for the specified item.

func collectionView(UICollectionView, canPerformAction: Selector, forItemAt: IndexPath, withSender: Any?) -> Bool
Asks the delegate if it can perform the specified action on an item in the collection view.

func collectionView(UICollectionView, performAction: Selector, forItemAt: IndexPath, withSender: Any?)
Tells the delegate to perform the specified action on an item in the collection view.

Managing Focus in a Collection View
func collectionView(UICollectionView, canFocusItemAt: IndexPath) -> Bool
Asks the delegate whether the item at the specified index path can be focused.

func indexPathForPreferredFocusedView(in: UICollectionView) -> IndexPath?
Asks the delegate for the index path of the cell that should be focused.

func collectionView(UICollectionView, shouldUpdateFocusIn: UICollectionViewFocusUpdateContext) -> Bool
Asks the delegate whether a change in focus should occur.

func collectionView(UICollectionView, didUpdateFocusIn: UICollectionViewFocusUpdateContext, with: UIFocusAnimationCoordinator)
Tells the delegate that a focus update occurred.

Controlling the Spring-Loading Behavior
func collectionView(UICollectionView, shouldSpringLoadItemAt: IndexPath, with: UISpringLoadedInteractionContext) -> Bool
Returns a Boolean value indicating whether you want the spring-loading interaction effect displayed for the specified item.


UICollectionViewDataSource Methods


Getting Item and Section Metrics
func collectionView(UICollectionView, numberOfItemsInSection: Int) -> Int  (Required)
Asks your data source object for the number of items in the specified section.

func numberOfSections(in: UICollectionView) -> Int
Asks your data source object for the number of sections in the collection view.

Getting Views for Items
func collectionView(UICollectionView, cellForItemAt: IndexPath) -> UICollectionViewCell  (Required)
Asks your data source object for the cell that corresponds to the specified item in the collection view.

func collectionView(UICollectionView, viewForSupplementaryElementOfKind: String, at: IndexPath) -> UICollectionReusableView
Asks your data source object to provide a supplementary view to display in the collection view.

Reordering Items
func collectionView(UICollectionView, canMoveItemAt: IndexPath) -> Bool
Asks your data source object whether the specified item can be moved to another location in the collection view.

func collectionView(UICollectionView, moveItemAt: IndexPath, to: IndexPath)
Tells your data source object to move the specified item to its new location.

Configuring an Index
func indexTitles(for: UICollectionView) -> [String]?
Asks the data source to return the titles for the index items to display for the collection view.

func collectionView(UICollectionView, indexPathForIndexTitle: String, at: Int) -> IndexPath
Asks the data source to return the index path of a collection view item that corresponds to one of your index entries.

What are collection types in objective C and Swift?

Ans : 

In  iOS, there are 3 collection types

i. Array 
ii. Dictionary 
iii. Set.

There are two types of collection types. Mutable and Immutable. Mutable can be changed but immutable can not be changed once initialised.

Q. How to check nil keys in dictionary?
A. There is not any nil keys in dictionary.

Do you like to use storyboard? Why? Can more than 1 storyboard allowed?

Ans : I like to use storyboard.

I am using storyboard due to advantage over XIB : See here

Yes, we can use more than 1 storyboard. We can make different storyboard for different features in same project.

Navigating from one storyboard to another storyboard :

1. Using segue :

  • Drag & Drop storyboard reference
  • Give name and assign viewcontroller (to which we want to navigate)
  • Give segue from viewcontroller to storyboard reference.
2. Using coding :


var anotherStoryboard = UIStoryboard(name: "another", bundle: nil)
var vc: UIViewController = anotherStoryboard.instantiateViewController(withIdentifier: "loginView")
present(vc, animated: false)




OOPS Concept in iOS

Ans :  OOPS Concepts are mostly same in all language. Their working are same but conditions are different.

1.      Inheritance : It allows a class to be defined that has a certain set of characteristics(methods and variables) and then other classes to be created which are derived from that class. The derived class inherits all of the features of the parent class and typically then adds some features of its own.

2.      Encapsulation : That binds data and functions together and keeps both safe from outside interference and misuse. Data encapsulation’s benefit of data hiding.

Data encapsulation is a mechanism of bundling the data and the functions that use them.

Data abstraction is a mechanism of exposing only the interface and hiding the implementation details from the user.


3. Polymorphism : Difference process depends on type. The method to be invoked is determined at runtime based on the type of the object. It is like override and overload.

Override : Different class, same method name with signature. It is also called runtime or dynamic polymorphism.

Overload : Same class, method name same with Different parameter. It is also called compile-time or static polymorphism. 


‌Which method is called first when app start?

Ans :

According to apple doc,


  • (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions{}
gets called before
  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{}

Difference between Strong and Weak in iOS

Ans : 


Strong
strong property means that you want to “own” the object. Only when you set the property to nil will the object be  destroyed. Unless one or more objects also have a strong reference to the object. This is the one you will use in most cases.
  1. Creates ownership between property and assigned value.
  1. This is default for object property in ARC so it does not let you worrying about reference count and release the reference automatically.
  1. It is replacement for retain. We use if and only if we need to use as retain.
  1. Retain count will be incremented.
  1. Creates non-ownerships between property and assigned value.
  1. Strong is used on parent object and weak is used on child object when parent is released then child object reference is also set to nil
  1. It helps to prevents retain cycles.
  1. It doesn’t protect the referenced object when collection by garbage collector.
  1. Weak is essentially assigned, un-retain property.
  1. Retain count will not be incremented.


Weak
Weak property means you don’t want to have control over the objects lifecycle. The object only lives on while another objects has a strong reference to it. If there are no strong references to the object then it will be destroyed. 
Weak reference is useful to avoid situation like retain cycle. Retain cycle occurs when two or more objects have strong reference to each other. This two object will never be freed in memory due to strong reference. So to avoid weak reference, One object has a strong ownership reference to another object, and another object should be have a weak reference to first object.

Strong references should be used when a parent object is referencing a child object and never the other way around. That is, a child class should not have a strong reference to the parent class.

Weak references should be used to avoid retain cycles and an object has the possibility to become nil at any point of it’s lifetime.

Good read : Click here




Difference between synchronous and asynchronous calls in Objective-C

Ans : 

Synchronous :
This call means task will be executed in order.
Asynchronous : This call means task may or may not be executed in order.

When call is called synchronously, then thread that initiated that operation will be wait to current task to be finished.
When call is called asynchronously, then it will not wait.

If we want to do some task without harassing UI, we can do those tasks in background thread. This goal is to keep free main thread, so it continuously respond UI event. So we can dispatch our task in background state asynchronously.

So for do task in background thread, we will divide in 2 parts.

1. GCD - Grand Central Dispatch. By using GCD, you have to grab one of global background queue or create your own background queue.

// one of the global concurrent background queues
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

// or you could create your own serial background queue:
// dispatch_queue_t queue = dispatch_queue_create("com.iosiqa.app.queuename", 0);

2. Dispatch your task to that queue asynchronously

dispatch_async(queue, ^{
    // task that to be done in background and it may be slow
});

The pattern for operation queues is very similar. Create an operation queue and add operations to that queue.

Lets see example :

Asynchronous call with Multithreading :

// Methods gets called in different thread and does not block the current thread.
[NSURLConnection sendAsynchronousRequest:request
                                   queue:queue
                       completionHandler:
    ^(NSURLResponse *response, NSData *data, NSError *error) {
}];

Synchronous call with Multithreading (not so useful):

//Do something
dispatch_sync(queue, ^{
    //Do something else // work in another queue or thread
});

//Do some more task


Access controls in Swift

Ans : 

Access controls
keyword enables you to hide the implementation details of your code, and to specify a preferred interface through which that code can be accessed and used.

Swift 3, Swift 4

There are 5 access controls.
1. open (most accessible, least restrictive)
2. public
3. internal (default)
4. fileprivate
5. private (least accessible, more restrictive)

1. open : It enable entity to be used in and outside of defining module and also other module. UIButton, UITableView is in UIKit. We import UIKit and make subclass of UITableView and use in our module in which we have imported UIKit. So tableview subclass of UITableView defined in UIKit is used in our module. Sot it is accessible in our module.

open class UITableView : UIScrollView, NSCoding { }

2. public : open allows us to subclass from another module. public allows us to subclass or override from within module in which it defined.

//module X
public func A(){}
open func B(){}

//module Y
override func A(){} // error
override func B(){} // success

So open class and class members can be accessible and overridden in which it is defined and also in which module it is imported.
public class and class members can be accessible and overridden only in which it is defined.


3. internal : Internal classes and members can be accessed anywhere within the same module(target) they are defined. You typically use internal-access when defining an app’s or a framework’s internal structure.

4. fileprivate : Restricts the use of an entity to its defining file. It is used to hide implementation details when details are used in entire file. fileprivate method is only accessible from that swift file in which it is defined.

5. private : Restricts the use of an entity to the enclosing declaration and to extension of that swift file or class. It is used to hide single block implementation. private entity can be accessible in swift 4 but it gives error in swift 3.




Explain MVC through implementation of UITableView

Ans :

Read first about MVC

Let's understand to implement UITableview in MVC

1. We write fetching data query or request web-service and parse json,xml and save data to any global variable like dictionary, array, etc. So all inserting, fetching methods and data variable are comes under M.....Model

2. We make custom tableview cell, and put various types of views like UILabel, UITextField, UIButton for displaying in UITableView on screen. So this comes under V....View.

3. For displaying TableView, we will take UIVIewController or UITableviewController. This are responsible for various activity like telling how many section, rows are there, on delete button deleting row, how much height of cell, etc... So this comes under C....Controller.

UITableviewDelegate and UITableViewDataSource Methods

Ans : 

UITableview's Delegate Methods :


The UIViewController in which UITableView you use must adopt the UITableViewDelegate protocol. Optional methods of the protocol allow the delegate to manage selections, configure section headings and footers, help to delete and reorder cells, and perform other actions.

Configuring Rows for the Table View

- tableView:heightForRowAtIndexPath:
- tableView:indentationLevelForRowAtIndexPath:
- tableView:willDisplayCell:forRowAtIndexPath:

Managing Accessory Views

- tableView:accessoryButtonTappedForRowWithIndexPath:
- tableView:accessoryTypeForRowWithIndexPath: Deprecated in iOS 3.0

Managing Selections

- tableView:willSelectRowAtIndexPath:
- tableView:didSelectRowAtIndexPath:
- tableView:willDeselectRowAtIndexPath:
- tableView:didDeselectRowAtIndexPath:

Modifying the Header and Footer of Sections

- tableView:viewForHeaderInSection:
- tableView:viewForFooterInSection:
- tableView:heightForHeaderInSection:
- tableView:heightForFooterInSection:

Editing Table Rows

- tableView:willBeginEditingRowAtIndexPath:
- tableView:didEndEditingRowAtIndexPath:
- tableView:editingStyleForRowAtIndexPath:
- tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:
- tableView:shouldIndentWhileEditingRowAtIndexPath:

Reordering Table Rows

- tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:

Copying and Pasting Row Content

- tableView:shouldShowMenuForRowAtIndexPath:
- tableView:canPerformAction:forRowAtIndexPath:withSender:
- tableView:performAction:forRowAtIndexPath:withSender: 








UITableview's Data Source Methods : The NSTableViewDataSource protocol declares the methods that an instance of NSTableView that provides the data to a table view and allows editing of the contents of its data source object.

All the methods are described in the following.

Getting Values

- numberOfRowsInTableView: (Required)
- numberOfSectionInTableView:
- cellForRowAtIndexPath : (Required)
- tableView:objectValueForTableColumn:row:

Setting Values

- tableView:setObjectValue:forTableColumn:row:

Implementing Pasteboard Support

- tableView:pasteboardWriterForRow:

Drag and Drop

- tableView:acceptDrop:row:dropOperation:
- tableView:namesOfPromisedFilesDroppedAtDestination:forDraggedRowsWithIndexes:
- tableView:validateDrop:proposedRow:proposedDropOperation:
- tableView:writeRowsWithIndexes:toPasteboard:
- tableView:draggingSession:willBeginAtPoint:forRowIndexes:
- tableView:updateDraggingItemsForDrag:
- tableView:draggingSession:endedAtPoint:operation:

Sorting

- tableView:sortDescriptorsDidChange:

Tips : UITableViewDelegate has no any required methods.

Class, Structs and Enum

Ans : 

Structs are value type, Class is reference type.
Structs are stored in stack, Class are stored in heap.

So, Structs are faster than class because of its memory management. (Read why stack allocation is more faster than heap)

Similarity between Class and Struct: 

Define properties to store values
Define methods to provide functionality
Be extended
Conform to protocols
Define intialisers
Define Subscripts to provide access to their variables

Only class can do:

Inheritance
Type casting
Define deinitialisers
Allow reference counting for multiple references.

When to use class and when to use struct?

--> When we want to maintain reference, then we should use class due to class is reference type. When not, we should use struct.

i.e 

Here's an example with a class. Note how when the name is changed, the instance referenced by both variables is updated. Bob is now Sue, everywhere that Bob was ever referenced.

class SomeClass {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var aClass = SomeClass(name: "Bob")
var bClass = aClass // aClass and bClass now reference the same instance!
bClass.name = "Sue"

println(aClass.name) // "Sue"
println(bClass.name) // "Sue"

And now with a struct we see that the values are copied and each variable keeps it's own set of values. When we set the name to Sue, the Bob struct in aStruct does not get changed.

struct SomeStruct {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var aStruct = SomeStruct(name: "Bob")
var bStruct = aStruct // aStruct and bStruct are two structs with the same value!
bStruct.name = "Sue"

println(aStruct.name) // "Bob"
println(bStruct.name) // "Sue"

So for representing a stateful complex entity, a class is awesome. But for values that are simply a measurement or bits of related data, a struct makes more sense so that you can easily copy them around and calculate with them or modify the values without fear of side effects.

Another theory for what to choose : 

Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple references to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multithreaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

With Structs, there is much less need to worry about memory leaks or multiple threads racing to access/modify a single instance of a variable. (For the more technically minded, the exception to that is when capturing a struct inside a closure because then it is actually capturing a reference to the instance unless you explicitly mark it to be copied).

Classes can also become bloated because a class can only inherit from a single superclass. That encourages us to create huge superclasses that encompass many different abilities that are only loosely related. Using protocols, especially with protocol extensions where you can provide implementations to protocols, allows you to eliminate the need for classes to achieve this sort of behavior.

The talk lays out these scenarios where classes are preferred:
  • Copying or comparing instances doesn't make sense (e.g., Window)
  • Instance lifetime is tied to external effects (e.g., TemporaryFile)
  • Instances are just "sinks"--write-only conduits to external state (e.g.CGContext)

Optional, Optional Binding, Unwrapping and Optional Chaining

Ans : 

Optional : Optional is swift's powerful feature which come to solve problem of  non-existing value. It is just a type . There are two types as Int (which must has a value) and Int?(which may contain a Int value or may have nil value). It is declared as T? i.e Int?, String?

Forced Unwrapping : Exclamation mark ( ! ) is used to unwrap value.
i.e let optionalInt : Int? = 5
let intVal : Int = 2
optionalInt! + intVal

So we hvae forecfully unwrap optionaInt. That means we tell compiler that optionalInt has a value and extract and use it.

But this is not good practise. If sometimes optionaInt has not value and we try to unwrap, then app will be crashed. A good practise is to check with nil before unwrapping or use optional binding. It checks it has value or not and if and only if it has value extract it and use it.

Optional Binding : You use optional binding to check if the optional contains a value or not. If it does contain a value, unwrap it and put it into a temporary constant or variable.

Example :

var stockCode:String? = findStockCode("Facebook")

let text = "Stock Code - "

if let tempStockCode = stockCode {

    let message = text + tempStockCode

    println(message)
}

The “if let” (or “if var”) are the two keywords of optional binding. In plain English, the code says “If stockCode contains a value, unwrap it, set its value to tempStockCode and execute the conditional block. Otherwise, just skip it the block”. As the tempStockCode is a new constant, you no longer need to use the ! suffix to access its value.

Implicitly Unwrapped Optional : When we are very very sure about it has value after first time it is set, then we need not unwrap every time. So for this type of scenario, we have to use it with ! mark in their type.

// forced unwrapping
let optionalInt: Int? = 123
let forcedInt: Int = optionalInt!

// implicitly unwrapped optional
let assumedInt: Int! = 123
let implicitInt: Int = assumedInt

It may has nil value.

Optional Chaining :

The feature allows us to chain multiple optionals together with the “?.” operator.


if let sharePrice = findStockCode("Apple")?.price {

    let totalCost = sharePrice * 100

    println(totalCost)

}

FindstockCode method returns optional value. We can access multiple optional together using Optional chaining feature.

Difference between Swift and Objective C

Ans : 

1. Swift is easier to read :

Swift removes @ symbol which exists in objective C.
Swift removes also legacy convention like semicolon at end of  statement.
Swift's method and function are easily called and [[ ]] are removed which exists in Objective C.

2. Swift is easier to maintain :

There are only 1 file to maintain name.swift. In objective c, there are .h and .m file for one viewcontroller or any views. So in swift, we have to maintain less files.

3. Swift is safe :

Optional type make the possibility of nil value very clearly, which means it generate compiler error as you write bad code instead of run time. So it reduce programmer's time due to not run the program for checking and resolve it after error coming run time.

4. Swift is robust in memory management :

ARC is available in Objective C but it supports only for Cocoa API and object oriented code. It does not support for procedural C code and Core Graphics API. So its programmer responsibility to mange memory. So it may have memory leak issue. Swift supports ARC for both procedural and object orientated code.

5. Swift less code :

+ sign concatenate two string in swift.
No need to remember value type token as %d, %s, %c like objective C. Swift does not require this type of token.

6. Swift is faster :

7. Swift supports dynamic library :

iOS doesn't support dynamic library untill released of swift and iOS 8.

8. Swift has playground :

Useful when programmar want to test 5 to 10 lines of code, he can test on playground instead of creating new application.






Multi threading, GCD, Operation Queue

Ans : 

1.
Thread : It is lightweight way to implement multiple paths of execution inside of an application.

2. Multi threading : iPhone CPU can only perform one operation at a time – once per clock cycle. Multi threading allows the processor to create concurrent threads it can switch between, so multiple tasks can be executed at the same time.

It appears as if the two threads are executed at the same time, because the processor switches rapidly between executing them. As a smartphone or desktop user, you don’t notice the switches because they occur so rapidly.

Multi threading allows a CPU to rapidly switch between multiple tasks in such a way that it appears as if the tasks are executed simultaneously.

You can’t update an app’s UI outside the main thread.

Race Condition  A race condition occurs when two tasks are executed concurrently, when they should be executed sequentially in order to be done correctly. You cant change view constraint while it is being calculated. So UI activity should be done in main thread so it is executed sequentially.


3. GCD : Grand Central Dispatch is a wrapper around creating threads and managing that code. Its emphasis is on dispatching. The Grand Central Dispatch (GCD) is a is a low-level API provided by Apple. GCD is used for managing concurrent operations. GCD has lots of benefits like

– It improves application performance and responsiveness.
– The app will become more smooth.
– Execute multiple tasks at a time or one by one as per your requirements.
GCD operates at the system level, it is managing the resources in a balanced way for all running application.



GCD & Operation Queues help keep your app user interface responsive by running slow task of main queue.

low_level_C coding :

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // Download file or perform expensive task

    dispatch_async(dispatch_get_main_queue()) {
        // Update the UI
    }
}

Swift 3+ code :

DispatchQueue.global(qos: .userInitiated).async {
    // Download file or perform expensive task

    DispatchQueue.main.async {
        // Update the UI
    }
}

There are 4 qos - quality of service level (Priority) from higher to low :

.userInteractive,
.userInitiated,
.utility
.background.

Learn more about QOS

For delaying task :

let delay = DispatchTime.now() + .seconds(60)
DispatchQueue.main.asyncAfter(deadline: delay) {
    // Dodge this!
}

Multi threading, GCD, Operation Queue

Ans : 

1.
Thread : It is lightweight way to implement multiple paths of execution inside of an application.

2. Multi threading : iPhone CPU can only perform one operation at a time – once per clock cycle. Multi threading allows the processor to create concurrent threads it can switch between, so multiple tasks can be executed at the same time.

It appears as if the two threads are executed at the same time, because the processor switches rapidly between executing them. As a smartphone or desktop user, you don’t notice the switches because they occur so rapidly.

Multi threading allows a CPU to rapidly switch between multiple tasks in such a way that it appears as if the tasks are executed simultaneously.

You can’t update an app’s UI outside the main thread.

Race Condition  A race condition occurs when two tasks are executed concurrently, when they should be executed sequentially in order to be done correctly. You cant change view constraint while it is being calculated. So UI activity should be done in main thread so it is executed sequentially.


3. GCD : Grand Central Dispatch is a wrapper around creating threads and managing that code. Its emphasis is on dispatching.

low_level_C coding :

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // Download file or perform expensive task

    dispatch_async(dispatch_get_main_queue()) {
        // Update the UI
    }
}

Swift 3+ code :

DispatchQueue.global(qos: .userInitiated).async {
    // Download file or perform expensive task

    DispatchQueue.main.async {
        // Update the UI
    }
}

There are 4 qos - quality of service level (Priority) from higher to low :

.userInteractive,
.userInitiated,
.utility
.background.

For delaying task :

let delay = DispatchTime.now() + .seconds(60)
DispatchQueue.main.asyncAfter(deadline: delay) {
    // Dodge this!
}

4. Operation Queue : 

Operations in Swift are a powerful way to separate responsibilities over several classes while keeping track of progress and dependencies. They’re formally known as NSOperations and used in combination with the OperationQueue.

An Operation is typically responsible for a single synchronous task. It’s an abstract class and never used directly. You can make use of the system-defined BlockOperation subclass or by creating your own subclass. You can start an operation by adding it to an OperationQueue or by manually calling the start method. However, it’s highly recommended to give full responsibility to the OperationQueue to manage the state.

//Making use of the system-defined BlockOperation looks as follows:

let blockOperation = BlockOperation {
    print("Executing!")
}

let queue = OperationQueue()
queue.addOperation(blockOperation)
//And can also be done by adding the block directly on the queue:

queue.addOperation {
  print("Executing!")
}

//The given task gets added to the OperationQueue that will start the execution as soon as possible.

Different states of an operation
An operation can be in several states, depending on its current execution status.
  • Ready: It’s prepared to start
  • Executing: The task is currently running
  • Finished: Once the process is completed
  • Canceled: The task canceled


What is subclassing?

Ans : Subclassing is way of inheriting property of one class to another class. Child class inherit all behaviour of parent class. Let's talk about UIImageView.

NSObject > UIResponder > UIView > UIImageView

I have made one class as SpecialImageView which inherit UIImageView.  So SpecialImageView is subclass and UIImageView is parent class.

Suppose I want  5 imageview in my viewcontroller, which has default behaviour like borderWidth =2, broderColor = blue. 

So I have written this behaviour in SpecialImageView class once. All those 5 images are as SpecialImageView instead of UIImageView. 

So I do not need to write to all this behaviour for every 5 imageviews. So subclassing gives benefit of customisation of any class.


When we want custom UITableViewCell then we need to make subclass of UITableViewCell.

How to find current location?

Ans : 

Framework : MapKit
Class : CLLocationManager
Delegate : CLLocationManagerDelegate

Write NSLocationAlwaysUsageDescription and also its description in info.plist file.

Code :

@IBAction func setCurrentLocation(sender: AnyObject) {
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest

            if self.locationManager.respondsToSelector(#selector(CLLocationManager.requestAlwaysAuthorization)) {
                locationManager.requestAlwaysAuthorization() // request for authorisation for first time when app open
            } else {
                 locationManager.startUpdatingLocation()
            }
        }
    }


 //Updated location

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

//Get last updated location(current)

        let location = locations.last! as CLLocation

        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)

        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.20, longitudeDelta: 0.20))

//Set region of current location in map view with zooming

        self.mpView.setRegion(region, animated: true)

//Show current location (blue dot) on map
        self.mpView.showsUserLocation = true

    }

What is category?

Ans : It is used to extend the functionality of the class. Implementation of category is in different file with name like classname + categoryname.h and .m file.

Read : Differnce between Category and Extension