Search Your Question

Showing posts with label Difference. Show all posts
Showing posts with label Difference. Show all posts

Difference between Swift and Objective C

Ans : 

1. Swift is easier to read :

Swift removes @ symbol which exists in objective C.
Swift removes also legacy convention like semicolon at end of  statement.
Swift's method and function are easily called and [[ ]] are removed which exists in Objective C.

2. Swift is easier to maintain :

There are only 1 file to maintain name.swift. In objective c, there are .h and .m file for one viewcontroller or any views. So in swift, we have to maintain less files.

3. Swift is safe :

Optional type make the possibility of nil value very clearly, which means it generate compiler error as you write bad code instead of run time. So it reduce programmer's time due to not run the program for checking and resolve it after error coming run time.

4. Swift is robust in memory management :

ARC is available in Objective C but it supports only for Cocoa API and object oriented code. It does not support for procedural C code and Core Graphics API. So its programmer responsibility to mange memory. So it may have memory leak issue. Swift supports ARC for both procedural and object orientated code.

5. Swift less code :

+ sign concatenate two string in swift.
No need to remember value type token as %d, %s, %c like objective C. Swift does not require this type of token.

6. Swift is faster :

7. Swift supports dynamic library :

iOS doesn't support dynamic library untill released of swift and iOS 8.

8. Swift has playground :

Useful when programmar want to test 5 to 10 lines of code, he can test on playground instead of creating new application.






Multi threading, GCD, Operation Queue

Ans : 

1.
Thread : It is lightweight way to implement multiple paths of execution inside of an application.

2. Multi threading : iPhone CPU can only perform one operation at a time – once per clock cycle. Multi threading allows the processor to create concurrent threads it can switch between, so multiple tasks can be executed at the same time.

It appears as if the two threads are executed at the same time, because the processor switches rapidly between executing them. As a smartphone or desktop user, you don’t notice the switches because they occur so rapidly.

Multi threading allows a CPU to rapidly switch between multiple tasks in such a way that it appears as if the tasks are executed simultaneously.

You can’t update an app’s UI outside the main thread.

Race Condition  A race condition occurs when two tasks are executed concurrently, when they should be executed sequentially in order to be done correctly. You cant change view constraint while it is being calculated. So UI activity should be done in main thread so it is executed sequentially.


3. GCD : Grand Central Dispatch is a wrapper around creating threads and managing that code. Its emphasis is on dispatching. The Grand Central Dispatch (GCD) is a is a low-level API provided by Apple. GCD is used for managing concurrent operations. GCD has lots of benefits like

– It improves application performance and responsiveness.
– The app will become more smooth.
– Execute multiple tasks at a time or one by one as per your requirements.
GCD operates at the system level, it is managing the resources in a balanced way for all running application.



GCD & Operation Queues help keep your app user interface responsive by running slow task of main queue.

low_level_C coding :

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // Download file or perform expensive task

    dispatch_async(dispatch_get_main_queue()) {
        // Update the UI
    }
}

Swift 3+ code :

DispatchQueue.global(qos: .userInitiated).async {
    // Download file or perform expensive task

    DispatchQueue.main.async {
        // Update the UI
    }
}

There are 4 qos - quality of service level (Priority) from higher to low :

.userInteractive,
.userInitiated,
.utility
.background.

Learn more about QOS

For delaying task :

let delay = DispatchTime.now() + .seconds(60)
DispatchQueue.main.asyncAfter(deadline: delay) {
    // Dodge this!
}

Multi threading, GCD, Operation Queue

Ans : 

1.
Thread : It is lightweight way to implement multiple paths of execution inside of an application.

2. Multi threading : iPhone CPU can only perform one operation at a time – once per clock cycle. Multi threading allows the processor to create concurrent threads it can switch between, so multiple tasks can be executed at the same time.

It appears as if the two threads are executed at the same time, because the processor switches rapidly between executing them. As a smartphone or desktop user, you don’t notice the switches because they occur so rapidly.

Multi threading allows a CPU to rapidly switch between multiple tasks in such a way that it appears as if the tasks are executed simultaneously.

You can’t update an app’s UI outside the main thread.

Race Condition  A race condition occurs when two tasks are executed concurrently, when they should be executed sequentially in order to be done correctly. You cant change view constraint while it is being calculated. So UI activity should be done in main thread so it is executed sequentially.


3. GCD : Grand Central Dispatch is a wrapper around creating threads and managing that code. Its emphasis is on dispatching.

low_level_C coding :

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // Download file or perform expensive task

    dispatch_async(dispatch_get_main_queue()) {
        // Update the UI
    }
}

Swift 3+ code :

DispatchQueue.global(qos: .userInitiated).async {
    // Download file or perform expensive task

    DispatchQueue.main.async {
        // Update the UI
    }
}

There are 4 qos - quality of service level (Priority) from higher to low :

.userInteractive,
.userInitiated,
.utility
.background.

For delaying task :

let delay = DispatchTime.now() + .seconds(60)
DispatchQueue.main.asyncAfter(deadline: delay) {
    // Dodge this!
}

4. Operation Queue : 

Operations in Swift are a powerful way to separate responsibilities over several classes while keeping track of progress and dependencies. They’re formally known as NSOperations and used in combination with the OperationQueue.

An Operation is typically responsible for a single synchronous task. It’s an abstract class and never used directly. You can make use of the system-defined BlockOperation subclass or by creating your own subclass. You can start an operation by adding it to an OperationQueue or by manually calling the start method. However, it’s highly recommended to give full responsibility to the OperationQueue to manage the state.

//Making use of the system-defined BlockOperation looks as follows:

let blockOperation = BlockOperation {
    print("Executing!")
}

let queue = OperationQueue()
queue.addOperation(blockOperation)
//And can also be done by adding the block directly on the queue:

queue.addOperation {
  print("Executing!")
}

//The given task gets added to the OperationQueue that will start the execution as soon as possible.

Different states of an operation
An operation can be in several states, depending on its current execution status.
  • Ready: It’s prepared to start
  • Executing: The task is currently running
  • Finished: Once the process is completed
  • Canceled: The task canceled


Difference between == and ===

Ans :  == checks equality and === checks identity. == check value of left side and right side are same or not. === check left side object and right side object point to same memory or not.

== used against int, float, string (value type) and === used against reference type (class type).

i.e

class SomeClass {
var a: Int;

init(_ a: Int) {
    self.a = a
}

}

var someClass1 = SomeClass(4)
var someClass2 = SomeClass(4)
someClass1 === someClass2 // false
someClass2 = someClass1
someClass1 === someClass2 // true

Difference between Static Constructor and Private Constructor

Ans : I have asked this question for C# language.

Private Constructor :  It is used to prevent class to be instantiated and to be inherited. Class can have multiple private constructor and can be called by any other constructor.

Static Constructor :   It is used to initialise static members of a class. We can't say when it is called and It is called by CLR and not called by manually. It is called just before first instance of class is created. Class can have a only one static constructor. This constructor is called only once in lifetime of application.

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];

Difference between Any and AnyObject

ANS : Swift has 2 types for working with  nonspecific type.
1. AnyObject
2. Any

1. AnyObject is for reference type(class) and Any is for both reference and value type.
2. AnyObject represent instance of only any class type, Any represent for any type including function type.

Note : It is always good practice to use specific type instead of Any, AnyObject.
After Swift 3.0, Objective C I'd type can be compatible with Swift Any type. Before that it is equivalent to AnyObject.
I.e
I have created dictionary in which I don't know what will be Value type.
[String : ?? ]
then ?? may be int, float, Array, Dictionary type.
So here we should use Any in replace of ??, because int, float are value type and array, dictionary are class type.
[ String : Any]

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 


Difference between Objective-C Category and Extension

Ans : 

1.Category is a way to add methods to a class whether or not source code is available implies you can add category to foundation classes like NSString and also to your own custom classes.

2.We can add extra instance variable and property in class extension but not in Category.

3.Any variable and method inside the extension is not even accessible to inherited class.

4.Category and Extension both are basically made to handle large code base but category is a way to extend class API in multiple source file while extension is a way to add required methods out side the main interface file.

5.Use category when you have to break your same class code into different source file according to different functionality and Extension when you just need to add some required methods to existing class outside the main interface file. also when you need to modify a publicly declared instance variable in a class. for ex: readonly to readwrite you can re declare it in extension.

Read : What is Category?

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.


Collectionview or Scrollview or PageViewController, Which one is most preferable?

It depends on requirement. If too many pages or items, then Collectionview or pageviewcontroller is good option. Because Collectionview can reuse cell for display view, whereas PageViewController load only current page,previous page and next page in memory. As Scrollview loads all subviews in memory, it will consume too much memory.

Pageviewcontroller load multiple viewcontroller in memory. So preferable most in following order :

1. UICollectionview
2. UIPageViewController
3. UIScrollView


UITableview and UICollectionview

Similarity :
The way to setup both with cell registration, dequeing cells, specifying size and heights are pretty much the same.

Diffrence :
1. The collection view is much more robust in terms of layout features and other things like animations.
Tableiw is a simple list, which displays single-dimensional rows of data. It’s smooth because of cell reuse and other magic.

2. UICollectionView is the model for displaying multidimensional data . 
UITableViewhas a couple of styles of cells stacked one over the other. You should not try to bend it to do any other kind of things too much complex than that kind of layout.

3. UICollectionView is a much more powerful set of classes that allow modifying almost every aspect of how your data will appear on the screen, especially its layout but also other things.

Advantage of Collectionview :
The biggest advantage of using collection view is the ability to scroll horizontally.
 If you want multiple columns in your apps then UICollectionView is the best way to do it. 


It is possible to have multiple columns in table view as well but it gets really messy since you are dealing with and array to display data in a table view.

UICollectionView Supports complex layouts. Apple provides you with something called UICollectionViewDelegateFlowLayout which provides you the flow of left and right as well as up and down.

UICollectionView supports custom animations based on different layouts which again cannot be done in UITableView.

Disadvantage of Collectionview (Advantage of Tablvieview over) :

Major disadvantages of using UICollectionView is auto sizing of your cells. It takes a lot of trial and error to get auto sizing to work correctly. UITableView wins here as all you have to do is return UITableView automatic dimensions for the height of your row in each one of your cells.

Summary :
If you need more control over your layout, go with UICollectionView, If you need simple list go with UITableview.