Wednesday, May 18, 2016

Objective-C Static vs Dynamic Typing

When declaring property we give the data type strongly If we know what is the data that the variable is going to hold like shown below.



     
NSString *userName;
     float employeeSalary;
     BOOL isAvailable;


This is Static Typing as we declared (fixed) the data type of those variables.


                         



Once we statically fix the data type of a variable, If we try to assign another data type value like shown below,



     
NSString *userName = 1; 


We will get a compile time error saying,

Implicit conversion of 'int' to 'NSString *' is disallowed in ARC

It means, we statically typed a variable and trying to assign a different data type.

What If we don't know the data type of a variable holding something?

For this, Objective-C has any object type called idid data type variables can hold any data type.



     
id someObject;


Let's take example of some JSON coming from a web service response. This JSON format could be an array () or a dictionary {}. In this case let take this response into an id and check the data type of the response using the NSObject introspection methods.

Please check my post Objective C NSObject Root Class to know what are introspection methods.



     
id response = NSURLResponse;

     if([id isKindOfClass:[NSArray class]]){

            // Response is in Array format
   
     }

     if([id isKindOfClass:[NSDictionary class]]){

           // Response is in Dictionary format
   
     }


With this example, Hope you have understood what is Dynamic Typing and it's use case in Objective-C programming. id enables Dynamic Typing in Objective C. The data type of object is decided at run time.

As per Apple's Documentation,


                         



A variable is dynamically typed when the type of the object it points to is not checked at compile time. Objective-C uses the id data type to represent a variable that is an object without specifying what sort of object it is. This is referred to as dynamic typing.

Dynamic typing contrasts with static typing, in which the system explicitly identifies the class to which an object belongs at compile time. Static type checking at compile time may ensure stricter data integrity, but in exchange for that integrity, dynamic typing gives your program much greater flexibility. And through object introspection (for example, asking a dynamically typed, anonymous object what its class is), you can still verify the type of an object at runtime and thus validate its suitability for a particular operation.



Hope this post is useful. Feel free to comment in case of any queries.

No comments:

Post a Comment