Search Your Question

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

What is singleton class? Pros and Cons.

Ans : The singleton pattern guarantees that only one instance of a class is instantiated. We are aware of following singleton classes,

// Shared URL Session
let sharedURLSession = URLSession.shared

// Default File Manager
let defaultFileManager = FileManager.default

// Standard User Defaults
let standardUserDefaults = UserDefaults.standard

Above classes are instantiate only once, if we try to create another instance, it returns also first instance. So through out application, only one instance is generated for singleton class.

Custom Singleton Class example: 

Different ways : 
1. When we need default configuration  (Using closure) : 

class NetworkManager {

    // MARK: - Properties

    private static var sharedNetworkManager: NetworkManager = {
        let networkManager = NetworkManager(baseURL: API.baseURL)
       // ....
       // Configuration
       // ....         return networkManager
    }()

    let baseURL: URL(string : "https://www.iosiqa.com")

    private init(baseURL: URL) {
        self.baseURL = baseURL
    }

    class func shared() -> NetworkManager {
        return sharedNetworkManager
    }
}

Use  : NetworkManager.shared().baseURL 

2. Using only single statement : 


class mpiosapp {
    
    static var shared = mpiosapp()
    let baseURL: URL(string : "https://www.iosiqa.com")
    private init(){}
    

}

Use : mpiosapp.shared.baseURL

Q : When static variable will be deinitialized?
A : Static variable will be deinit when program or app stops working.

Disadvantage of Singleton :

1. One of the main disadvantages of singletons is that they make unit testing very hard. They introduce global state to the application. The problem is that you cannot completely isolate classes dependent on singletons. When you are trying to test such a class, you inevitably test the Singleton as well. When unit testing, you want the class to be as loosely coupled with other classes as possible and all the dependencies of the class should be ideally provided externally (either by constructor or setters), so they can be easily mocked. Unfortunately, that is not possible with singletons as they introduce tight coupling and the class retrieves the instance on its own. But it gets even worse. The global state of stateful singletons is preserved between test cases.

2. It is static so memory will not be freeze until app will killed. It has it's own creation time and its own lifecycle.

3. Singletons create hidden dependencies. As the Singleton is readily available throughout the code base, it can be overused. Moreover, since its reference is not completely transparent while passing to different methods, it becomes difficult to track. (To solve that we should pass singleton object variable as parameter and this way is called dependency injection).



How many ways to pass data from one view controller to another view controller?

Ans :

Through following methods, we can pass data from one viewcontroller to another viewcontroller.

1. Using segue (PrepareForSegue) method,
2. Delegate
3. Setting variable

Let's assume we have 2 viewcontroller named VC1 and VC2. We want to pass data from VC1 to VC2 and some times VC2 to VC1. For both cases, we can use segue to pass data. But in general practise, to pass data from VC1 to VC2 (Forward data passing), we use segue and from VC2 to VC1(Backward data passing), we use protocol - delegate way.

1. Using segue (PrepareForSegue) steps :  VC1 --->  VC2


  •   Draw segue from VC1 to VC2 and give identifier string 'InputVCToDisplayVC'  to segue.
  •   Take variable in VC2.swift as :

           var fullName : String?

  •    In VC1, write following code in PrepareForSegue method,


       override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "InputVCToDisplayVC"){
let displayVC = segue.destination as! DisplayViewController
displayVC.fullName = nameTextField.text
        }
        }

  •       In VC2, viewDidLoad, we can get  value of fullName and access it.
2. Using delegate steps :    VC2  --->  VC1


Import UIKit

class VC1: UIViewController, VC2Delegate {


       override func viewDidLoad() {
                super.viewDidLoad()
                
       }

       func doSomething(data : String) {
                print(data)
      }


      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if(segue.identifier == "InputVCToDisplayVC"){
      let displayVC = segue.destination as! DisplayViewController
      displayVC.delegate = self
      }
       }

 }


Import UIKit
protocol VC2Delegate {
      func doSomething(data : String) 
}

class VC2 : UIViewController {
        
      var fullName : String?
      weak var delegate : VC2Delegate?
      
      override func viewDidLoad() {
             
     }

     @IBAction func btnPassToVC1_TouchUpInside(_ sender : UIButton) {
              if let delegate = delegate {
                     delegate.doSomething(data: btn.titleLabel.text)       
              }
    }
}


In above, method we make custom protocol and create its object as delegate.We set delegate reference to VC1. So on VC2 button pressed event, VC1 doSomething method will be called.

3. Setting Variable steps :     VC1   --->  VC2

  • Take variable in VC2.swift as :  
           var fullName : String?

  • On buttonPressed action of VC1, write code as :
           let vc2 : VC2 =  UIStoryboard(name: "Main", bundle:                                                                                                        nil).instantiateViewController(withIdentifier: "VC2_ID") as! VC2
           vc2.fullName = "iOS iQA"
           self.present(vc2, animated: true, completion: nil)

Note : There are also persistent storage, by which we can store data and access that data any where in our project. But this is not correct answer or solution for above question or problem. We can store data in NSUserDefault, PList, Coredata, SQLite, KeyChain Access, File as persistent storage.






    

What is lazy property?

Ans : 

When to use lazy initialization is when the initial value for a property is not known until after the object is initialized.

For example, if you have a Person class and a personalizedGreeting property. The personalizedGreeting property can be lazily instantiated after the object is created so it can contain the name of the person.

class Person {      
  var name: String
    
  lazy var personalizedGreeting: String = {
    return "Hello, \(self.name)!"
  }()
    
  init(name: String) {
    self.name = name
  }
}

When you initialize a person, their personal greeting hasn’t been created yet:

let person = Person(name: "John Doe") // person.personalizedGreeting is nil But when you attempt to print out the personalized greeting, it’s calculated on-the-fly:

NSLog(person.personalizedGreeting)

Bonus Tip : You do need to declare your lazy property using the var keyword, not the let keyword, because constants must always have a value before initialization completes.

Benefit of lazy property increase performance in terms of speed.

Explain defer keyword or defer statement in Swift

Ans : Defer block is executed just before return statement or exit of block. Let's have a look to following chunk of code for better understanding

      func defer()  { 
          print("Start") 
          var value: String? 
         defer { 
              if let v = value { 
                   print("Ending execution of \(v)")
              } 
        } 
      value = "defer function" 
      print("End") 
   }

So printing sequence is like following :

Start
End
Ending execution of defer function

So in short defer block will be called lastly in the current block. It will be executed in any case like before return, before the break, before throw exception. Yes, if exception comes, then also defer block will be called before program crash or going to exception.

If there is multiple defer block in same method, Then defer block will execute from down to up side.


Difference between Swift Array and Objective C Array

Ans : Swift arrays (Array and for short, []) are passed by value which means
that every object contained will be copied.

NSArray are implemented as classes (and bridged from ObjC) so they're passed as references.

In Swift, we can declare three type of array.
One is Array or [],
Second is NSArray,
Third is NSMutableArray.

NSArray and NSMutableArray are coming from Objective C by bridge. So interviewer may ask what are difference between types arrays in swift?

Extract value from Array : 

Get 3rd Value from Array

Objective C : [arr objectAtIndex:2] // 2 due to index start from 0 in array

Swift : arr[2] 

Determine index of one integer in another integer - online programming question

Problem Description : Determine index of one integer in another integer

i.e If input A = 23,B = 1472367 then Output : 3 . Because '23' is 3rd index in '1472367'.

Asked in Company : Futurescape Technologies Pvt Ltd  via Codility.com

Ans : 

#import <Foundation/Foundation.h>
// you can also use other imports, for example:
// #import <SomeLibrary/SomeFile.h>

// you can write to stdout for debugging purposes, e.g.
// printf("this is a debug message\n");

int solution(int A, int B) {
    // write your code in Objective-C 2.0
    NSString *strA = [NSString stringWithFormat:@"%d",A];
    NSString *strB = [NSString stringWithFormat:@"%d",B];
 
   NSRange range =   [strB rangeOfString:strA];
   if(range.location == NSNotFound)
   return -1;
   else
   return range.location;
}


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

Why array method containObject has id as parameter in ios?

Ans : id is a generic type. This means that the compiler will expect any object type there, and will not enforce restrictions. It can be useful if you're expecting to use more than one class of objects there. So you can add anything of type id to an NSArray.

So array method containObject has id type as parameter.

- (BOOL)containsObject:(ObjectType)anObject;

Usage :

bool bVal = [arr containObject:@5];

Difference between blocks and completion handler in iOS

Ans :

Blocks:

Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary.

They can be executed in a later time, and not when the code of the scope they have been implemented is being executed.
Their usage leads eventually to a much cleaner and tidier code writing, as they can be used instead of delegate methods, written just in one place and not spread to many files.
Syntax: ReturnType (^blockName)(Parameters)

see example:

int anInteger = 42;

void (^testBlock)(void) = ^{

    NSLog(@"Integer is: %i", anInteger);   // anInteger outside variables

};

// calling blocks like
testBlock();
Block with argument:

double (^multiplyTwoValues)(double, double) =

                          ^(double firstValue, double secondValue) {

                              return firstValue * secondValue;

                          };
// calling with parameter
double result = multiplyTwoValues(2,4);

NSLog(@"The result is %f", result);





Completion handler:
Whereas completion handler is a way (technique) for implementing callback functionality using blocks.
A completion handler is nothing more than a simple block declaration passed as a parameter to a method that needs to make a callback at a later time.
Note: completion handler should always be the last parameter in a method. A method can have as many arguments as you want, but always have the completion handler as the last argument in the parameters list.
Example:
- (void)beginTaskWithName:(NSString *)name completion:(void(^)(void))callback;
// calling
[self beginTaskWithName:@"MyTask" completion:^{
    NSLog(@"Task completed ..");
}];
More example with UIKit classes methods.

[self presentViewController:viewController animated:YES completion:^{
        NSLog(@"xyz View Controller presented ..");
        // Other code related to view controller presentation...
    }];
[UIView animateWithDuration:0.5
                     animations:^{
                         // Animation-related code here...
                         [self.view setAlpha:0.5];
                     }
                     completion:^(BOOL finished) {
                         // Any completion handler related code here...
                         NSLog(@"Animation over..");
                     }];

Why tableview cell separator leave some space before?

Ans : 




Alternatively, you can also edit this in interface builder (IB):
  1. Go to IB.
  2. Select Table View.
  3. Open "Attribute Inspector" on the right.
  4. Change "Separator Insets" from Default to Custom.
  5. Change the "Left" attribute from 15 to 0.
15 is default. So Left side space is seen before cell seperator.

Do you know SMTP? is it use SOAP or REST?

Ans : 

SMTP : 
SMTP (Simple Mail Transfer Protocol) is a TCP/IP protocol used in sending and receiving e-mail.

SOAP and REST both allow you to create your own API. API stands for Application Programming Interface. It makes it possible to transfer data from an application to other applications. An API receives requests and sends back responses through internet protocols such as HTTP, SMTP, and others.

It use SOAP web-service. SOAP is protocol and rules are maintained by World wide web consortium(W3C).

Design such button in that text should be displayed below image

Ans : 




1) Select button and go to Attribute Inspector in your storyboard.

2) Assign Image to the button. (Don't use background Image)

3) Set Title text to that button.

4) Now you need to set edge and Inset so first select image from edge and set Inset as you need and then select title from edge and set inset as per your need.

Difference between viewdidload and viewwillappear?

Ans : 


ViewDidLoad - It is excecuted once. So writer settings like set label text in ViewDidLoad.
ViewWillAppear - It is called every time when view appear.


ViewDidLoad - It is called when view is begin constructed.
ViewWillAppear - When view is about ready to appear.


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
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.


Suppose your tableview data will be changed periodically. Then you have to write [tableview reloaddata] in ViewWillApper.

Read UIViewController LifeCycle

What are blocks in iOS?

Ans : 

Blocks are first-class functions, which is a fancy way of saying that Blocks are regular Objective-C objects. Since they’re objects, they can be passed as parameters, returned from methods and functions, and assigned to variables. A block creates a const copy of any local variable that is referenced inside of its scope.

Block is a chunk of code that can be executed at some future time.

Blocks can greatly simplify code. They can help you reduce code, reduce dependency on delegates, and write cleaner, more readable code.

Block is alternative of delegate or NSNotificationCenter. In delegate and NSNotificationCenter, callback methods and main method are written different places. So its more difficult to read. In block, call back method written in main method as parameter.

Declaration : return_type (^block_name)(param_type, param_type, ...)
int (^add)(int,int)

Definition : ^return_type(param_type param_name, param_type param_name, ...) { ... return return_type; }
^(int number1, int number2){ return number1+number2 }

Declaration + Definition : 

int (^add)(int,int) = ^(int number1, int number2){ return number1+number2; }

We can call block also like following : 

int resultFromBlock = add(2,2);

If we take example of NSArray using block :


[theArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){

    NSLog(@"The object at index %d is %@",idx,obj);

}];



If we take example of UIView animation using block :

[UIView animateWithDuration:5.0 
                     animations:^{
                        [animatingView setAlpha:0];
                        [animatingView setCenter:CGPointMake(animatingView.center.x+50.0, 
                                                             animatingView.center.y+50.0)];
                     } 
                     completion:^(BOOL finished) {
                         [animatingView removeFromSuperview];
                     }];

Apple also suggest to use block instead of call back methods.

Difference between blocks and completion handler : 

We have understand what is block. Completion handler is a way (technique) for implementing callback functionality using blocks. As a completion handler parameter, we have to pass block.

Example of Completion handler is seen above as last example of blocks.

Completion handler always comes as last parameter.

Read more : Difference between blocks and completion handler



Expandable tableview Logic in iOS

Ans : 

Logic  : 

  • Display UITableView containing just the header/section titles for each category.
  • When a section is touched, expand it if it is not already expanded. Otherwise, collapse the section.
  • When a section is touched, expand it and if another section is currently expanded collapse that section so that only one section is expanded at a time.
  • To expand a section, determine the number of items that must be displayed within that section and insert that number of rows in the UITableView; then display the items in the newly inserted rows.
  • To collapse a section, determine the number of items currently displayed within that section and delete that number of rows from the UITableView.

To reload one section only : 

[self.tableView beginUpdates];
 (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation:
[self.tableView endUpdates];

Difference between XIB and Storyboard

Ans : 


XIB :

1) Xib files are used with a single UIView.

3)It's utilizes more memory as compared to storyboard and quiet slow.

4) It is compatible from iOS5 and onwards

5) You can do localizations for different languages and countries using different XIBs .

6) It's difficult to use same Xib to support multiple devices.

Storyboard :

1)You can layout all your Scenes like View Controllers, Nav Controllers, TabBar Controllers, etc in a single storyboard.

3)Usually fast and allocates less memory.

4)It's not compatible prior to iOS 5 .

5)"Dynamic" and "Prototype" cells can be used easily.

6)Storyboards best to use for the apps with a small to medium amount of screens.

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


Difference between thread-safe and non-thread-safe in iOS

Ans : 

Thread-Unsafe -> If any object allow to modify by more than one thread at the same time.  (non-atomic property is thread-unsafe. Comments are welcomed)

Thread-safe -> If any object not allow to modify by more than one thread at the same time.Immutable objects are generally thread-safe. (atomic property attribute type. Comments are  welcomed)

In general, immutable classes like NSArray, let are thread-safe, while their mutable variants like NSMutableArray,var are thread-unsafe.



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.