Search Your Question

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.



Which type of encryption you have used in iOS App?

Ans : I have used trippleDES for passing data in request to server.

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicPostDict options:kNilOptions error:&error];

 NSString *strJsonData=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

 NSData *encryptedJsonString = [CommonMethods tripleDesEncryptString:strJsonData  key:@"2-055PL&okjnnhkey@inihgr" error:nil];
 NSString *strencryptedJsonString = [encryptedJsonString base64Encoding];

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.




MVC in iOS

Ans : The main goal of MVC pattern is separate data/logic, view and controller. There are 3 layers.

1. Model : Models are representation of your app's data. There is user class or struct. So it has fields like name, birthdate, etc. It is data reside in Model layer.

2. View : It is object which user can see and interact with. UILabel showing text is one kind of view.

3. Controller : Controller mediates between Model and View. It takes data from model and show on views and also update model when user interacts with view.

File Structure :

MVC File Structure


Understand MVC using UITableView

Explain MVC through implementation of UITableView

Ans :

Read first about MVC

Let's understand to implement UITableview in MVC

1. We write fetching data query or request web-service and parse json,xml and save data to any global variable like dictionary, array, etc. So all inserting, fetching methods and data variable are comes under M.....Model

2. We make custom tableview cell, and put various types of views like UILabel, UITextField, UIButton for displaying in UITableView on screen. So this comes under V....View.

3. For displaying TableView, we will take UIVIewController or UITableviewController. This are responsible for various activity like telling how many section, rows are there, on delete button deleting row, how much height of cell, etc... So this comes under C....Controller.

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