Thursday, 30 March 2017

CoreData Migration


Migration :

Every persistent store is bind to particular version of data model by keeping reference of data model identifier. If data model changes, we need to tell Core Data how to migrate the date of persistent store to new data model version. 

There are two type of migration :

1. Light Weight Migration: It Uses CoreData ability to infer model schemas change automatically and can be easily used when  add or remove entities, attributes and modify relationship between them. Apple recommends to take advantage of light weight migration whenever possible.

2. Heavy Weight Migration: It require complex process and require developer to manage different mapping files and write complicated , verbose policy to manually shuttle data different data model.  

Mapping Model :  It define how one version of data model is related to other version.


Why We Need CoreData Migration:

Whenever we edit schema of our Application data model we need to tell CoreData about change in data model of persistent store coordinator. if user doesn't perform data migration then application will crash and giving 

fatal error -- "The model used to open the store is incompatible with the one used to create the store";

Perform Data Migration

1. Add Version in data model 

Select DataModel and then go to Editor and select Add Model Version like in below screen 






Enter Version name as shown in below screen and click on Finish button :






2. In Project Navigator we can see different data model along with current data model selected.
Green checkmark represent active data model.


3. Perform Migration : 

For Implementing Light weight migration we need to pass two keys in option parameter of  addPresistentStore( ofType : configurationName : at : options : ) method in our CoreData Manager class 


This methods Accept dictionary as last parameter so for supporting light weight we will pass two dictionary of option with two keys as :

  a. NSInferMappingModelAutomaticallyOption :  Pass TRUE — CoreData attempts
 to infer mapping model for migration based on data model version.

  b. NSMigratePresistentStoresAutomaticallyOption: Pass TRUE — Will Indicate CoreData to automatically perform migration if there is any change in data model.


Complete Code would look like as :




 do {
                let options = [ NSInferMappingModelAutomaticallyOption : true,
                                NSMigratePersistentStoresAutomaticallyOption : true]

                try coordinator!.addPersistentStore(ofType: NSXMLStoreType, configurationName: nil, at: url, options: options)

            } catch {
                // Replace this implementation with code to handle the error appropriately.
                 
                /*
                 Typical reasons for an error here include:
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                failError = error as NSError
            }


 Code highlighted in the below image:





Now  application will run successfully without any fatal error that occur when we migrate data from one data model version to other.

We can now easily Add , remove new entity , attributes and define relation between them.


Wednesday, 7 September 2016

Basic theory for IOS Interview


Basic Things to know as an IOS Developer  

Property:
Properties ensure that the instance variable of the class can be accessed outside the class. Properties begin with @property, which is a keyword 
=> Properties is followed with access specifiers, which are nonatomic or atomic, readwrite or readonly and strong, unsafe_unretained or weak. 
=> This varies based on the type of the variable. For any pointer type, we can use strong, unsafe_unretained or weak. Similarly for other types we can use readwrite or readonly. 

What is Keyword Atomic and NonAtomic in Objective-C ? 

Atomic Keyword will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. 
=> Properties are atomic by default . 
=> Atomic Keyword is Thread Safe. 
=> That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A. 

In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than "atomic". NonAtomic Keyword does not guarantees about thread safety. 
=> If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell. 

What is NSSet ? 
An NSSet object represents a static, unordered collection of distinct objects. NSSet is immutable, so you cannot add or remove elements from a set after it’s been created. You can, however, alter mutable objects that are contained in the set. 
An NSSet can be created through the setWithObjects: class method, which accepts a nil-terminated list of objects. 
An NSSet instance can record any kind of Objective-C object, and it does not have to be homogeneous. 

What is NSArray and NSMutableArray ? 
NSArray and its subclass NSMutableArray manage ordered collections of objects called arrays. NSArray creates static arrays, and NSMutableArray creates dynamic arrays. You can use arrays when you need an ordered collection of objects. 

What is Synchronization ? 
Synchronization is defined as a mechanism which ensures that two or more concurrent processes or threads do not simultaneously execute some particular program segment known as mutual exclusion. When one thread starts executing the critical section (serialized segment of the program) the other thread should wait until the first thread finishes. 
If proper synchronization techniques are not applied, it may cause a race condition where, the values of variables may be unpredictable and vary depending on the timings of context switches of the processes or threads. 


Define NSThread ? 

An NSThread object controls a thread of execution.
Threads are especially useful when you need to perform a lengthy task, but don’t want it to block the 

execution of the rest of the application. In particular, you can use threads to avoid blocking the main thread of the application, which handles user interface and event-related actions. Threads can also be used to divide a large job into several smaller jobs, which can lead to performance increases on multi- core computers. 

What is Retain Count or Reference Counting? 

Retain Count is the term which is related to the Manual Memory Management 

=> When we create a object, Objective C doesn't really care about the object we have created , the area of memory is claimed for this object and retain count is increased by one.
And whenever we release that object the retain count does go down by one . 


=>When the retain count of object reaches zero, Objective C blows that object ( memory occupied by object will be free ) and it will be ready to reclaim that memory for another Object. 

What you mean by Asynchronous and GCD in Objective-C ? 

Grand Central Dispatch, or GCD for short, is a C API that makes it exceptionally easy to perform asynchronous operations in iOS. 

Asynchronous operations are a fundamental part of every iOS app when you want to perform long operations without freezing or blocking the user interface. You can image that if your entire app froze without warning then your users would get quite irritated. 

With GCD, you can line up blocks of code in a queue for the system to execute as necessary. These blocks or operations, will be dispatched in the queue to another thread, leaving your main UI thread to continue its tasks. 

It’s important to know that GCD will use separate threads for it’s operations but which thread it isn’t important to you. All that matters is that your long running process in a separate thread outside the 
main thread where your UI and gestures are running. 

What are Blocks : 

=> Block is a chunk of code that can be executed at some future time. 
=> 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. 
=> Blocks are Objective-C objects. Block objects are one type of C-level syntactic and runtime features. Blocks, in addition to executable code in standard C functions, they may also comprise variable bindings to managed (heap) or automatic (stack) memory. Therefore, a block can preserve a set of data that it can use to affect behaviour when executed. They can be added to collections like NSArray or NSDictionary. 

Override Getter and Setter Method : 

In Objective-C, we use @property to provide managed access to the state of a class. The system provides basic management rules like thread locking and reference retainment. To provide custom access logic,we need to write your own getter and setter methods. 
Let’s say that we have a Customer class and its name must always be in upper case. First, we declare the property in the interface: 

@interface Customer
@property (nonatomic) NSString* name; @end 

Next, we do the implementation. 
@implementation Customer @synthesize name = _name; //Must do this 
//Setter method
- (void) setName:(NSString *)n { 

NSLog(@"Setting name to: %@", n); 
_name =n; } 
//Getter method
- (NSString*) name { 

NSLog(@"Returning name: %@", _name); 
return _name; } 
- (void) test {
self.name = @“Prashant ”; NSLog(@"Name is %@", self.name); 

}
 @end 

Here, we are declaring a member variable called _name that is mapped to the name property. The setter method is called setName. The getter method is just name. 


What is Design Pattern ? 

Design patterns are reusable solutions to common problems in software design. They’re templates designed to help you write code that’s easy to understand and reuse. They also help you create loosely coupled code so that you can change or replace components in your code without too much of a hassle. 
The most common Cocoa design patterns: 
Creational: Singleton and Abstract Factory.Structural: MVC, Decorator, Adapter, Facade and Composite. Behavioral: Observer, Memento, Chain of Responsibility and Command. 

Model View Controller (MVC): 

Model View Controller (MVC) is one of the building blocks of Cocoa and is undoubtedly the most-used design pattern of all. It classifies objects according to their general role in your application and encourages clean separation of code based on role.
The three roles are: 
Model: The object that holds your application data and defines how to manipulate it. For example, in your application the Model is your Album class. 

View: The objects that are in charge of the visual representation of the Model and the controls the user can interact with; basically, all the UIViews and their subclasses. In your application the View is represented by your AlbumViewclass. 

Controller: The controller is the mediator that coordinates all the work. It accesses the data from the model and displays it with the views, listens to events and manipulates the data as necessary. Can you guess which class is your controller? That’s right: ViewController

The Singleton Pattern 
The Singleton design pattern ensures that only one instance exists for a given class and that there’s a global access point to that instance. It usually uses lazy loading to create the single instance when it’s needed the first time.
Apple uses this approach a lot. 
For example:
[NSUserDefaults standardUserDefaults]
[UIApplication sharedApplication]
[UIScreen mainScreen]
 [NSFileManager defaultManager]all return a Singleton object

Interface for Singleton Class is quite straightforward, we declare a class method so that it can be called directly with class name.

#import <Foundation/Foundation.h>
 
@interface MySingleton : NSObject
 
#pragma mark -
#pragma mark Class Methods
+ (MySingleton *)singletonObject;
 
@end


Implementation
#import "MySingleton.h"
 
@implementation MySingleton
 
#pragma mark -
#pragma mark Class Methods
+ (MySingleton *) singletonObject {
    static MySingleton *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[self alloc] init];
    });
     
    return _sharedInstance;
}
 
@end


The implementation is simple. We declare a static variable _sharedInstance will hold a reference to the singleton object. We invoke dispatch_once, aGrand Central Dispatch function, and pass in a block in which we initialize an instance of the MySingleton class. We store a reference to the instance  in _sharedInstance.

The dispatch_once function ensures that the block we pass it is executed once for the lifetime of the application. This is very important since we only want to initialize one instance of the MySingleton class.
The oncePredicate variable that is passed as the first argument of thedispatch_once function is used by the dispatch_once function to ensure that the block is executed only once.
The singletonObject class method returns the MySingleton instance by returning the reference stored in _sharedInstance

The Decorator Design Pattern 

The Decorator pattern dynamically adds behaviors and responsibilities to an object without modifying its code. It’s an alternative to subclassing where you modify a class’ behavior by wrapping it with another object.
In Objective-C there are two 
very common implementations of this pattern: 

Category and Delegation.
Category

Category is an extremely powerful mechanism that allows you to add methods to existing classes without subclassing. The new methods are added at compile time and can be executed like normal methods of the extended class. It’s slightly different from the classic definition of a decorator, because a Category doesn’t hold an instance of the class it extends. 

Delegation 

The other Decorator design pattern, Delegation, is a mechanism in which one object acts on behalf of, or in coordination with, another object. For example, when you use aUITableView, one of the methods you must implement istableView:numberOfRowsInSection:.
You can’t expect the 
UITableView to know how many rows you want to have in each section, as this is application-specific. Therefore, the task of calculating the amount of rows in each section is passed 
on to the UITableView delegate. This allows the UITableView class to be independent of the data it displays. 

The Observer Pattern 

In the Observer pattern, one object notifies other objects of any state changes. The objects involved don’t need to know about one another – thus encouraging a decoupled design. This pattern’s most often used to notify interested objects when a property has changed.
The usual implementation requires that an observer registers interest in the state of another object. When the state changes, all the observing objects are notified of the change. Apple’s Push Notification service is a global example of this.
If you want to stick to the MVC concept (hint: you do), you need to allow Model objects to communicate with View objects, but without direct references between them. And that’s where the Observer pattern comes in.

Cocoa implements the observer pattern in two familiar ways: 
Notifications and Key-Value Observing (KVO)

Notification :

Notifications are based on a subscribe-and-publish model that allows an object (the publisher) to send messages to other objects (subscribers/listeners). The publisher never needs to know anything about the subscribers.
Notifications are heavily used by Apple.


For example, when the keyboard is shown/hidden the system sends a
UIKeyboardWillShowNotification/UIKeyboardWillHideNotification, respectively. When your app goes to the background, the system sends aUIApplicationDidEnterBackgroundNotificationnotification. 

Key-Value Observing (KVO) 

In KVO, an object can ask to be notified of any changes to a specific property; either its own or that of another object. 

Encryption and Decryption: 

Encryption is the process of translating plain text data (plaintext) into something that appears to be random and meaningless (ciphertext).

Decryption is the process of converting ciphertext back to plaintext. 

To encrypt more than a small amount of data, symmetric encryption is used.
A symmetric key is used during both the encryption and decryption processes. To decrypt a particular piece of ciphertext, the key that was used to encrypt the data must be used.

The goal of every encryption algorithm is to make it as difficult as possible to decrypt the generated ciphertext without using the key. If a really good encryption algorithm is used, there is no technique significantly better than methodically trying every possible key. For such an algorithm, the longer the key, the more difficult it is to decrypt a piece of ciphertext without possessing the key. 
OS X and iOS provide a number of encryption technologies. Of these, three APIs are available on both iOS and OS X: 
Keychain Services API—provides secure storage for passwords, keys, and so on
Cryptographic Message Syntax—provides (nonstreaming) symmetric and asymmetric encryption and 

decryption
Certificate, Key, and Trust Services—provides cryptographic support services and trust validation 


What is TCP And UDP ?

There are two types of Internet Protocol (IP) traffic. They are TCP orTransmission Control Protocol and UDP or User Datagram Protocol.
TCP is connection oriented – once a connection is established, data can be sent bidirectional.
UDP is a simpler, connectionless Internet protocol. Multiple messages are sent as packets in chunks 
using UDP. 
Difference between TCP and UDP 
TCP 
UDP 
Reliability: TCP is connection- oriented protocol. When a file or message send it will get delivered unless connections fails. If connection lost, the server will request the lost part. There is no corruption while transferring a message. 
Reliability: UDP is connectionless protocol. When you a send a data or message, you don't know if it'll get there, it could get lost on the way. There may be corruption while transferring a message. 
Ordered: If you send two messages along a connection, one after the other, you know the first message will get there first. You don't have to worry about data arriving in the wrong order. 
Ordered: If you send two messages out, you don't know what order they'll arrive in i.e. no ordered 
Heavyweight: - when the low level parts of the TCP "stream" arrive in the wrong order, resend requests have to be sent, and all the out of sequence parts have to be put back together, so requires a bit of work to piece together. 
Lightweight: No ordering of messages, no tracking connections, etc. It's just fire and forget! This means it's a lot quicker, and the network card / OS have to do very little work to translate the data back from the packets. 
Streaming: Data is read as a 
Datagrams: Packets are sent individually 

"stream," with nothing distinguishing where one packet ends and another begins. There may be multiple packets per read call. 
and are guaranteed to be whole if they arrive. One packet per one read call. 
Examples: World Wide Web (Apache TCP port 80), e-mail (SMTP TCP port 25 Postfix MTA), File Transfer Protocol (FTP port 21) and Secure Shell (OpenSSH port 22) etc. 
Examples: Domain Name System (DNS UDP port 53), streaming media applications such as IPTV or movies, Voice over IP (VoIP), Trivial File Transfer Protocol (TFTP) and online multiplayer games etc 

What is dispatch_once ? 
The behavior of dispatch_once is in the name. It does something once and only once. 
It takes two parameters. The first is a predicate that tracks the "once". The second is a block to execute on the first call. Calls look like this: 
static dispatch_once_t predicate; dispatch_once(&predicate, ^{ 
// some one-time task 
});
It's a great API for lazily initializing shared state, whether it's a global dictionary, a singleton instance, a cache, or anything else that needs a bit of setup the first time through. 


What is a .dSYM and How can we use it?

dSYM files store the debug symbols for your app
Services like crashlytics uses it to replace the symbols in the crash logs with the appropriate methods names so it will be readable and will make sense.
the benefit of using the dSYM is that you don't need to ship your App with it symbols making it harder to reverse engineer it and also reduce your binary size
in order to use it in order to symbolicate the crash log you need to drag the crash log into the device's device logs in the organizer of the machine that compiled the app binary (a machine that stores the dSYM)