Search Your Question

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

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)
    }
}


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

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

Difference between Sqlite and CoreData

Ans  : Sqlite is database and Coredata is Object Relational Model which is layer between UI and Database. Coredata is memory efficient and Querying to Sqlite is not so efficient.
So we can't compare Sqlite and Coredata. Both are different thing.


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.

What is StackView? What is advantage and distribution type of stackview?

Ans : Stack View allows to layout views in a stack in either horizontal or vertical fashion. In Xcode-7, stackview is introduced.

Advantage : Stacks are containers that keep views aligned automatically.

Distribution Types :

Fill(Default) : When you place your controls inside a UIStackView with Fill set as the distribution, it will keep all but one of the controls at their natural size and stretch one of them to fill the space. It determines which control to stretch by noting which one has the lowest Content Hugging Priority (CHP).

Fill Equally : With this type, each control in a UIStackView will be of equal size. All of the space between the controls will be used up, if possible. I added a spacing of eight between the UITextFields, so again you could see the size of each one. With this type, the CHP does not matter, because each control is the same size.

Fill Proportionally : The UIStackView will ensure the controls maintain the same proportion relative to one another as your layout grows and shrinks. Unlike the previous two settings, the Fill Proportionally distribution needs the controls to have an intrinsic content size. The Fill and Fill Equally distribution tell their child controls how big they should be, but this one is the other way around (as long as there is enough space for all of your controls to be their natural size). The proportions for the images and labels are maintained for the different layout sizes.

Equal Spacing : This distribution type will maintain an equal spacing between each of the controls and will not resize the controls themselves.

Equal Centring :  It will equally space the centres of the controls. Space between every control is equal.