Search Your Question

Showing posts with label Zomato. Show all posts
Showing posts with label Zomato. Show all posts

What is Unmanaged objects?

Ans : 


In rare cases, Core Foundation function may return a C-pointer or an object reference embedded into an Unmanaged wrapper. You must transfer Unmanaged references into the normal memory management system before working with them in Swift.

An Unmanaged wrapper, like an Optional wrapper, provides a layer of safety between your code and a potentially nasty crash.  The Unmanaged<T> type stores a pointer whose memory is not controlled by the Swift runtime system. Before using this data, you take responsibility for how this memory should stay alive.


Different types of Control statements.

Ans. 

Control flow statements are used to control the flow of execution in a program.

1. Loop Statement : 

For-in

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")

}


While 
var i:Int = 0
while i < 10 {
    print(i)
    i += 1
}

repeat-while
var j: Int = 10
repeat {
   print(j)
}
while(j < 10)

2. Branch Statement : 

If-else
var numArray = [10, 20, 30, 40, 50, 60, 70]
if(numArray.contains(20)){
    print("true it contains 20")
}else{
    print("number is not there")
}

guard
guard condition else {
    statements
}

The else clause of a guard statement is required, and must either call a function with the Never return type or transfer program control outside the guard statement’s enclosing scope using one of the following statements:  
  • return 
  • break 
  • continue
  •  throw
Switch
switch grade {
    
case 90 ..< 100:
    print("A")
case (80 ..< 90):
    print("B")
case (70 ..< 80):
    print("C")
case (0 ..< 70):
    print("D")
    
default:
    print("F. You failed")//Any number less than 0 or greater than 99
    
}

3. Control Transfer Statement : 
continue 
let numbersArray = [20, 30, 40, 50, 60, 70, 80, 90, 10]
for num in numbersArray{
    if(num > 10){
        continue
    }
    print(num)
}

// prints: 10

break 
let numbersArray = [20, 30, 40, 50, 60, 70, 80, 90, 10]
for num in numbersArray{
    if num > 30{
        break
    }
    print(num)
}


fallthrough : switch statements don’t fallthrough the bottom of each case and into the next one. That is, the entire switch statement completes its execution as soon as the first matching case is completed.

for num in numbersArray{
    switch num {
    case 10:
        print(num)
    case 20:
        print(num)
    case 30:
        print(num)
        fallthrough
    case 40:
        print(num)
    default:
        print("nothing here")
    }
}

return :
func myFunc() -> Int {
    let myNumber = 16 % 3
    if myNumber == 0 {
        return 0
    }
    else if myNumber == 1 {
        return 1
    }
    return 0
}

throw
enum ErrorsToThrow: Error {
    case fileNotFound
    case fileNotReadable
    case fileSizeIsTooHigh
}
class documents {
    
    init() {
        do {
            let dataFromString = try? readFiles(path: "")
            print(dataFromString)
        } catch ErrorsToThrow.fileNotFound {
            print("error generated1")
        } catch ErrorsToThrow.fileNotReadable {
            print("error generated2")
        } catch ErrorsToThrow.fileSizeIsTooHigh {
            print("error generated3")
        } catch {
                print("error")
        }
    }
    
func readFiles(path:String) throws  ->String {
        if path == "" {
            throw ErrorsToThrow.fileNotFound
        }
        return "Data from file"

    }
}



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.




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)

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

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 frames and bounds.

Ans : 

Frame :  View's location and size using the parent view's coordinate system
Needed while placing the view in the parent

bounds = View's location and size using its own coordinate system
Needed while placing the view's content or subviews within itself

The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).

The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.

So, imagine a view that has a size of  50x50 (width x height) positioned at 15,15 (x,y) of its superview. The following code prints out this view's bounds and frame:

NSLog(@"bounds.origin.x: %f", label.bounds.origin.x);
NSLog(@"bounds.origin.y: %f", label.bounds.origin.y);
NSLog(@"bounds.size.width: %f", label.bounds.size.width);
NSLog(@"bounds.size.height: %f", label.bounds.size.height);

NSLog(@"frame.origin.x: %f", label.frame.origin.x);
NSLog(@"frame.origin.y: %f", label.frame.origin.y);
NSLog(@"frame.size.width: %f", label.frame.size.width);
NSLog(@"frame.size.height: %f", label.frame.size.height);

Output : 

bounds.origin.x: 0
bounds.origin.y: 0
bounds.size.width: 50
bounds.size.height: 50

frame.origin.x: 15
frame.origin.y: 15
frame.size.width: 50
frame.size.height: 50

So, we can see that in both cases, the width and the height of the view is the same regardless of whether we are looking at the bounds or frame. What is different is the x,y positioning of the view. In the case of the bounds, the x and y coordinates are at 0,0 as these coordinates are relative to the view itself. However, the frame x and y coordinates are relative to the position of the view within the parent view (which earlier we said was at 25,25).

For more understanding : Visit this 


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.