Search Your Question

Showing posts with label Swift. Show all posts
Showing posts with label Swift. Show all posts

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.

Dynamically set UITableview cell height

Ans : 

For auto cell height in tableview in Swift 3.0

Write following 2 lines of code in viewDidLoad and before reload tableview :

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44

Following steps must to do otherwise label height will not be increase and so UITableiViewCell.

Label height must be auto incremented using numberOfLines = 0

LineBreak should be set according your need word-wrap, char-wrap, etc...

ARC - Automatic Reference Counting

Ans : Automatic Reference Counting is memory management feature in iOS that provides automatic referencing counting system. According to attribute type of property like retain and release, it increment and decrements reference count at runtime.

ARC is does not handle reference cycle automatically. 

Unlike garbage collection, ARC does not handle reference cycles automatically.


Default property attributes : 

i> Memory management : strong  weak  copy  assign 
ii> Thread Safety : atomic nonatomic
iii> Mutability : readwrite readonly

@property (strong, atomic, readwrite) NSArray *name;

For IBOutlet,

@property (nonatomic, retain) IBOutlet UILabel *label;


@property (weak) IBOutlet UILabel *instructions;
In 2015, apple recommend to use Strong.


To stop retain cycle, user should mention weak reference when needed.

Q : What is retain?
A.Retain works same as Strong according to apple document. If we assign retain, it will convert to strong or consider as Strong. 

Read : Difference between Strong and Weak attribute

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.

Difference between == and ===

Ans :  == checks equality and === checks identity. == check value of left side and right side are same or not. === check left side object and right side object point to same memory or not.

== used against int, float, string (value type) and === used against reference type (class type).

i.e

class SomeClass {
var a: Int;

init(_ a: Int) {
    self.a = a
}

}

var someClass1 = SomeClass(4)
var someClass2 = SomeClass(4)
someClass1 === someClass2 // false
someClass2 = someClass1
someClass1 === someClass2 // true

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 protocol? Why it is used?

Ans : Protocols are way to specify a set of methods that class has to implement if class want to work with this protocol. Protocol has 2 types of methods like Required type and Optional type methods.

1. If @required are tagged above methods, then these methods must be implemented on class which confirm this protocol.

2. If @optional are tagged above methods, then these methods is not necessary to implement on it.

Why it is used? 

Protocol provide blueprint methods for classes. It has certain methods and parameters that classes have to implement in its body. Its like that classes should have certain characteristic if it confirm protocol. Like if you want to become human(class) you must be sleep, eat, breathe(characteristics).

For more detail,
I have created Delegate and Protocol. See example.

What are higher order functinos in swift?

Ans : Higher order functions are functions that operate on other functions by taking function as argument or returning function.

 Sorted : Sorting array. It may takes closure as argument and returns array .
let numbers : [Int] =  [1,5,2,4,3]
let arrNumbers = numbers.sorted()

By default it returns in ascending order.

numbers.sorted(by: (Int,Int) -> Bool)  - > How we want to sort array then sorted(by:)
numbers.sorted((a,b) -> Bool in return a > b } // descending order
numbers.sorted(by : >)

      Map : It iterates through the array that is calling it and changes each element of the array based on the closure passes to the method.

Use map to loop over a collection and apply the same

operation to each element in the collection. It returns after

applying transform.

let arrInt = [1,8,4,6]
I want add 1 in every number in array.
Without loop, using map,

arrInt.map( $0 + 1)  // <- This is shortest code for doing map

output : [2,9,5,7]

How map works :

The map function has a single argument which is a closure (a

function) that it calls as it loops over the collection. This

closure takes the element from the collection as an argument and

returns a result. The map function returns these results in an

array.

Another example :

let chocolateAmt = [“Dairy Milk”:20.0, “Munch”:10]

I want to increase price 5%,
so using map,
chocolateAmt.map{ (key, value) in
   value + value*0.05
      }

output : [“Dairy Milk”:21.0, “Munch”:10.5]

Another Example :

If we want index in map,

let arrInt = [1, 2, 4, 5]
let indexElement = arrInt.enumerated().map { (index,element) in
return "\(index):\(element)"
}
print(indexElement) // [“0:1”, “1:2”, “2:4”, “3:5”]

CompactMap: Use this method to receive an array of nonoptional values when your transformation produces an optional value.

let scores = ["1", "2", "three", "four", "5"]

let mapped: [Int?] = scores.map { str in Int(str) }
// [1, 2, nil, nil, 5] - Two nil values as "three" and "four" are strings.

let compactMapped: [Int] = scores.compactMap { str in Int(str) }
// [1, 2, 5] - The nil values for "three" and "four" are filtered out. 


FlatMapFlatmap is used to flatten a collection of collections.

Flatmap is joined word of Flat + Map. So as per name, it applies map function over collection and do flatten collection.


Test 1 :

let codes = [["abc","def","ghi"],["jkl","mno","pqr"]]
let newCodes = codes.flatMap { $0.map {$0.uppercased()} }
print(newCodes)


Output : ["ABC","DEF","GHI","JKL","MNO","PQR"] 


Test 2 :

let codes = ["abc","def","ghi"]
let newCodes = codes.flatMap { $0.uppercased() }
print(newCodes)

Output : ["A","B","C","D","E","F","G","H","I"]

-> In Test 2, first it applies map so half output is like 

["ABC","DEF","GHI"] and after that it applies flat so now full 

output is : ["A","B","C","D","E","F","G","H","I"]


Tip : 

1. String is collection from Swift 4.

2.If you do flatmap a collection containing optional values, 

flatmap will only consider the non-nil values.

let codes = [1,2,nil,3,nil,5]

let newCodesFlatMap = codes.flatMap { return $0 }
output : [1,2,3,5]


let newCodesFlatMap = codes.map { return $0 }

output : [optional(1),optional(2),nil,optional(3),nil,optional(5)]


The output of map became a collection of optional int ([Int?]) 



only because the array had nil — value in it. Otherwise it would 



have been an Int array. It is benefit of using flatMap.



Filter : Return array with elements which fulfill filter condition.           
let numbersLessThanFive = numbers.filter { (a) -> bool in return a  <  5 }
let numbersLessThanFive = numbers.filter { $0 < 5}

          Reduce : It is used to combine all element in array to make one single value.
let sumOfNumbers = numbers.reduce(0, { $0 + $1 }) 

Difference between map and flatmap : 

Big difference is Map considers nil but flatmap  remove nil value from collection.


Difference between Delegate and NSNotification

Ans :  A delegate uses protocol and creates a has-a relationship between two classes. Benefit of delegate is that we can return something back to the owning class.
Notification is like point to multi-point communication. Notification is one way  of message transmitting way.

Delegates create relationship between two classes. Notifications are used to send events to one or many classes.

We have to use delegate to specified known object. Notification for all object.

Delegate is like talking over telephone. Notification is like radio station.  

Coding of NSNotificationCenter :

[[NSNotificationCenter defaultCenter] addObjserver:self selector:@selector(useNotificationWithString:)  name:@”TimeOut” object:nil];

For BroadCast,

[[NSNotificationCenter defaultCenter] postNotificationName:@”TimeOut” object:nil userInfo:dict];

-(void) useNotificationWithString:(NSNotification *)notification
{
            dict = [notification userInfo];
}

To Remove observer,
[[NSNotificationCenter defaultCenter] removeObserver];

What is delegate?

Ans : Delegate is means of communication between objects of iOS Applications. Delegate allows one object to send message to another object when an event occurs.

i.e
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”title” message:@”message” delegate:self cancelButtonTitle:@”Ok” otherButtonTitle:nil];

Here delegate is self. So now self is responsible for handling  all event fired by this instance of UIAlertView class.

Which button of UIAlertView is clicked, for that, event is clickedButtonAtIndex is called in or by Self or currentViewController.

Create PreDefined delegate :

  1. There are two ViewController NameVC and SurNameVC.
  2.  In NameVC, there are 2 textfield named as Name and FullName and 1 button as Submit.
  3. If I write in name and click on submit, it went to SurNameVC to take Surname parameter.
  4. On SurNameVC, after write Surname, on clicking of Submit, It call delegate method and went back to NameVC and Print Full Name in FullName textfield.

Implement above delegate and protocol in Objective-C : 


I have made protocol on SurNameVC like
    @protocol SurNameVCDelegate
      -(void)setSurName:(NSString *) strSurName;
    @end
    
    @property (nonatomic, retain) id delegate;

Now on NameVC submit button click, choose delegate of  SurNameVC object as self.

   objSurNameVC.delegate = self

and create method -(void)setSurName:(NSString *) strSurName;

on NameVC and it is called from surNameVC submit button. So setSurName is delegate method. We can print fullname by concatenating Name and Surname in FullName textfield.

So we delegate just pass message from one view controller to another view controller by delegate method.

Implement delegate and protocol in Swift

I have made custom UISlider. I want to send some value from custom UISlider value changed to view controller in which it is used. So for that, I have used delegate - protocol method.

customSlider.swift  Custom Slider file


import UIKit
protocol SliderDelegate: class {
    func sliderValueChanged(_ sender : UISlider)
}


class mpgpsSlider: UIView {
     
      weak var delegateSliderDelegate?

      required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)
        
        let bundle = Bundle.init(for: type(of: self))
        let nib = UINib(nibName: "Slider", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        addSubview(view)
        
        slider.addTarget(self, action: #selector(sliderValueChanged(_:)), for:                  .valueChanged)
    }

     @objc func sliderValueChanged(_ sender : UISlider)  {
        delegate?.sliderValueChanged(sender)
      }

}

ViewController.swift ViewController in which custom slider is used.

import UIKit

class VehicleProfileVC: BaseViewController,SliderDelegate{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        slider.delegate = self
    }
    
    func sliderValueChanged(_ sender: UISlider) {
        label.text = String(sender.value)
    }
}


Difference between Any and AnyObject

ANS : Swift has 2 types for working with  nonspecific type.
1. AnyObject
2. Any

1. AnyObject is for reference type(class) and Any is for both reference and value type.
2. AnyObject represent instance of only any class type, Any represent for any type including function type.

Note : It is always good practice to use specific type instead of Any, AnyObject.
After Swift 3.0, Objective C I'd type can be compatible with Swift Any type. Before that it is equivalent to AnyObject.
I.e
I have created dictionary in which I don't know what will be Value type.
[String : ?? ]
then ?? may be int, float, Array, Dictionary type.
So here we should use Any in replace of ??, because int, float are value type and array, dictionary are class type.
[ String : Any]

What is the nil coalescing operator in swift?

Ans : 

Swift has very powerful in terms of safety because it has feature of optional.

Optional may be has value or may be not. So we try to assign some optional to any another string or any type, then it comes some problem.

Nil Coalescing operator is solution of above problem.

let myname : String = nil
let unwrappedname = myname ?? "Default"

It checks if myname is nill then Default will be assigned to unwrappedname.
So unwrappedname is type of String instead of String?.

Such way nil Coalescing operator ?? is very useful in Swift.


UIViewcontroller Lifecycle

Ans : A view controller manages set of views and making user interface. It will coordinate with data and other controller. Views are automatically loaded when view property is accessed in the app.
Following methods are used to mange view controller's view.

1. LoadView : It is automatically called when it's view property is accessed. It loads or create a view and assigned to property.

2. ViewDidLoad : It is automatically called when view controller completely loaded into memory. Override this method to perform additional initialization on views that were loaded from xib.
I.e instance variable initialization, database access, network request

Event Management to Views :

1. ViewWillAppear : It is called when View is about to added on view hierachy. If we want to change some, then we have to override this method.
Like change orientation, change screen data

2. ViewDidAppear : It is called when view was added on view's hierachy.
When we need to display loader, start UI animation ,then override this method.

3. ViewWillDisAppear : It is called when view is about to removed from hierachy. We can hide keyboard,  commit changes ,revert changes in this method by overriding.

4. ViewDidDisappear : It is called when view is removed from hierachy. We can remove cache data in this method.

Memmory Management method :
1. didReceiveMemoryWarning :
It is called automatically when system determine that the system has low amount of available memory.
Override this method remove not essential data from memory.


Ordering of excecuting methods :

1. Init(coder:)
2. (void)loadView
3. (void)viewDidLoad
4. (void)viewWillAppear
5. (void)viewDidAppear
6. (void)didReceiveMemoryWarning
7. (void)viewWillDisappear
8. (void)viewDidDisappear

Difference between Objective-C Category and Extension

Ans : 

1.Category is a way to add methods to a class whether or not source code is available implies you can add category to foundation classes like NSString and also to your own custom classes.

2.We can add extra instance variable and property in class extension but not in Category.

3.Any variable and method inside the extension is not even accessible to inherited class.

4.Category and Extension both are basically made to handle large code base but category is a way to extend class API in multiple source file while extension is a way to add required methods out side the main interface file.

5.Use category when you have to break your same class code into different source file according to different functionality and Extension when you just need to add some required methods to existing class outside the main interface file. also when you need to modify a publicly declared instance variable in a class. for ex: readonly to readwrite you can re declare it in extension.

Read : What is Category?

What is extension and How to use it?

Ans :
Swift Extension :

Add a new swift file with File > New > File... > iOS > Source > Swift File, but you can call them what you want.
The general naming convention is to call it TypeName+NewFunctionality.swift

Make extension of Double

Double+Conversions.swift

import Swift // or Foundation

extension Double {

    func celToFahren() -> Double {
        return self * 9 / 5 + 32
    }

    func fahrenToCel() -> Double {
        return (self - 32) * 5 / 9
    }
}

How to make extension:

let boilingPointCel = 100.0
let boilingPointFaren = boilingPointCel.celToFahren()
print(boilingPointFaren) // 212.0

Make extension of UIColor

UIColor+CustomColor.swift

import UIKit

extension UIColor {

    class var customGreen: UIColor {
        let darkGreen = 0x008110
        return UIColor.rgb(fromHex: darkGreen)
    }

    class func rgb(fromHex: Int) -> UIColor {

        let red =   CGFloat((fromHex & 0xFF0000) >> 16) / 0xFF
        let green = CGFloat((fromHex & 0x00FF00) >> 8) / 0xFF
        let blue =  CGFloat(fromHex & 0x0000FF) / 0xFF
        let alpha = CGFloat(1.0)

        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }

}
See here also.

Using extension :

view.backgroundColor = UIColor.customGreen

Summary : Once you define an extension it can be used anywhere in your app just like the built in class functions. In Objective-C extensions are known as categories.

Objective C Extension : 

In objective c, when you want to make behavior of some property private you use class extension.
-> it comes with .m file only.
-> mainly for properties.
The implementation of the extension must be in the main @implementation block of the file.
Extension can only be added to the classes whose source code is available because compiler compile the source code and extension at same time.

Difference between Delegate and Datasource

Ans :

A delegate type object responds to actions that another object takes.
i.e  the UITableViewDelegate protocol has methods such as didSelectRowAtIndexPath for performing actions upon a user selecting a particular row in a table and willDisplayCell which called before delegate use cell to draw row.

DataSource type object gives data to another object.
i.e UITableViewDataSource protocol has methods such as cellForRowAtIndexPath and numberOfSectionInTaboeView dictating what should be displayed in the table.

Understanding Delegate in More Detail : 

If Object X call Object Y to perform an action. Object X should know when Object Y complete task and take action after that. 

Here we can tell that X is delegate object of Y. Y will have a reference of X. So X will implement delegate methods of Y. So Y can notify to X via delegate method.

One more point we can say that Delegate about controlling of UI and DataSource about controlling data.

Buy CHRYOSOLITE Superman Fan Art Men's Round Neck TShirt

What are persistent storage in iOS and Which one is most secure?

Ans : There are SIX types of persistent storage.

1. Userdefaut
2. Property List
3. Sqlite
4. Keychain
5. Files
6. Coredata

If brief answer they asked then follow :

1. Userdefaut : NSUserDefault class allow us to store small amount of data. It can store NSData, NSString, NSArray, NSDictionary,  NSNumber,
The maximum data can we saved depends on iOS. Currently it can store 4GB of data.
But if file is too large, then it takes too much time for retrieve and write data in file. So we can save small amount of data only. Otherwise it waste time.
We can also store our custom objects in userDefaults. We achieve this by conforming our class to NSCoding protocol. We can then convert our custom object into NSData with the help of NSKeyArchiver class. The NSData is then stored into userDefaults like other objects. Similarly we can get NSData from userDefaults and then using NSKeyUnarchiver convert the NSData back to our custom objects.

2. Property List : As userdefaut save data in plist file, so like userdefaut, Property List is not also made for save large amount of data. There is one method of NSArray and NSDictionary as writeToFile for saving data.

3. Sqlite : If your application deals with large amount of data with relationship then we should use sqlite. It's API is written in C language and embedded with our application so it is very fast. There are ORM for bringing gap between obj c app and sqlite like, FMDB,  Realm

4. Keychain : If you want to save highly sensitive and secure data like passwords and secret codes then there is a good news for you. Storing data in keychain is most secure way. To store data, I have taken library named SwiftKeyChainWrapper from cocoapods.

To Save data in Keychain : 

let saveSuccessful: Bool = KeychainWrapper.standard.set("Some String", forKey: "myKey")

To get data from Keychain :

let retrievedPassword: String? = KeychainWrapper.standard.string(forKey: "userPassword")

To remove data from keychain : 

let removeSuccessful: Bool = KeychainWrapper.standard.remove(key: "myKey")

5. Files : You can save data to any type of file. There are three type of folder like Document, Library, Tmp fo saving various type of file.

6. Core Data : Apple’s solution for persistence allows applications to persist data of any form and retrieve it. It  isn’t technically a database, although it usually stores its data in one (an SQLite DB). It’s not an object-relational mapper (ORM), though it can feel like one. It’s truly an object graph, allowing you to create, store, and retrieve objects that have attributes and relationships to other objects. Its simplicity and power allow you to persist data of any form, from basic data models to complex.