Search Your Question

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

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.




Which delegate method called when I click on push notifications?

Ans : 
Different app delegate method called depends on following scenarios

For silent notification : 

App is in Foreground
No system alert shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Background
System alert is shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Suspended
App state changes to Background
System alert is shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is Not Running because killed by user
System alert is shown
No callback is called

Normal Push Notification (no content-available) :

App is in Foreground
No system alert shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Background or Suspended
System alert is shown
No method is called, but when user tap on the push and the app is opened
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Not Running
System alert is shown
No method is called, but when user tap on the push and the app is opened
application:didFinishLaunchingWithOptions: then application:didReceiveRemoteNotification:fetchCompletionHandler: are both called

Query for last inserted row in SQL database

Ans. 

If column is primary key and integer, then ,

Sqlite : SELECT * FROM table ORDER BY column DESC LIMIT 1;

or

SELECT * FROM table WHERE ID = SELECT LAST_INSERT_ROWID()

FMDB : 

Last inserted id is : [fmdb lastInsertRowId];

Sqlite3 all functions : 

sqlite3_open: This function is used to create and open a database file. It accepts two parameters, where the first one is the database file name, and the second a handler to the database. If the file does not exist, then it creates it first and then it opens it, otherwise it just opens it.
sqlite3_prepare_v2: The purpose of this function is to get a SQL statement (a query) in string format, and convert it to an executable format recognisable by SQLite3.
sqlite3_step: This function actually executes a SQL statement (query) prepared with the previous function. It can be called just once for executable queries (insert, update, delete), or multiple times when retrieving data. It’s important to have in mind that it can’t be called prior to the sqlite3_preprare_v2 function.
sqlite3_column_count: This method’s name it makes it easy to understand what is about. It returns the total number of columns (fields) a contained in a table.
sqlite3_column_text: This method returns the contents of a column in text format, actually a C string (char *) value. It accepts two parameters: The first one is the query converted (compiled) to a SQLite statement, and the second one is the index of the column.
sqlite3_column_name: It returns the name of a column, and its parameters are the same to the previous function’s.
sqlite3_changes: It actually returns the number of the affected rows, after the execution of a query.
sqlite3_last_insert_rowid: It returns the last inserted row’s ID.
sqlite3_errmsg: It returns the description of a SQLite error.
sqlite3_finalize: It deletes a prepared statement from memory.

sqlite3_close: It closes an open database connection. It should be called after having finished any data exchange with the database, as it releases any reserved system resources.