Showing posts with label Introspection. Show all posts
Showing posts with label Introspection. Show all posts

Wednesday, May 25, 2016

Objective-C SEL and @selector

SEL is a data type like int, NSString, NSArray etc.... Which holds kind of method signature. @selector gives the kind of method signature to us.

Let's discuss in detail with an example. 


   
- (void)doSomething1{
    
       NSLog(@"doSomething1");
   }

   - (void)doSomething2:(NSString*)val{
    
        NSLog(@"doSomething2:%@",val);
   }

   - (void)doSomething3:(NSString*)val1 withAnotherObject:(NSString*)val2 {
    
         NSLog(@"doSomething3:%@:%@",val1,val2);
   }



  
  SEL myMethod1 = @selector(doSomething1);
    SEL myMethod2 = @selector(doSomething2:);
    SEL myMethod3 = @selector(doSomething3:withAnotherObject:);


These are useful,

#1 When we need to do introspection before calling methods.


       
    if([self respondsToSelector: myMethod1])
    {
        
        // Same as [myObj doSomething1];
        [self performSelector: myMethod1];   
    }
    
    if([self respondsToSelector: myMethod2])
    {

        // Same as [myObj doSomething2:@"val"];
        [self performSelector:myMethod2 withObject:@"val"];   
     }
    
     if([self respondsToSelector: myMethod3])
     {

        // [myObj doSomething3:@"val1" withAnotherObject:@"val2"];
        [self performSelector:myMethod3 withObject:@"val1" withObject:@"val2"];  
     }



Calling, [self performSelector:myMethod2], will give EXC_BAD_ACCESS as we are supposed to pass a parameter which we didn't.


                         




#2 When we need to run a simple background operation


  
[self performSelectorInBackground:myMethod2 withObject:@"iOSSolves"];



#3 When we need to run something on Main thread while we are in a background thread


  
[self performSelectorOnMainThread:myMethod2 withObject:@"iOSSolves" 
                                                                                         waitUntilDone:YES];


#4 When we need to run something after a particular delay



  
[self performSelector:myMethod2 withObject:@"iOSSolves" afterDelay:2.0];


performSelector works for methods having max 2 parameters. If a method is having more than 2 parameters, It doesn't work. We need to go for NSInvocation for that situation.



                         


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

Wednesday, May 18, 2016

Objective C 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 id. id 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.

Wednesday, September 16, 2015

Objective C NSObject Root Class

All the Objective C programmers know that the root class of all Objective C classes is NSObject. It is part of NSFoundation framework. Root class inherits from no other class. Let's see why it a root class and what it gives us to maintain that big name called 'Root Class'.

Here I am just detailing the information given in the Apple Documentation. I feel like the information is briefed in that documentation. I Just want to discuss in detail on this topic in this article. So If any one finds it similar to that apple documentation, please don't come back here and call me a copy cat :)

1. NSObject declares the fundamental object interface and 
    implements basic object behaviour.

2. NSObject gives us Introspection methods :

  • Methods like isKindOfClass and isMemberOfClass, to determine if an object inherits directly or indirectly from a particular class. For more information on these methods, checkout out my article here.
  • Methods like respondsToSelector, to find out if an object's class or super class implements a method.
  • Methods like confirmsToProtocol, to find out if a class confirms a particular protocol or not.


      So from this, and also as per the Apple Documentation,


  • You can call introspection methods as runtime checks to help you avoid problems such as exceptions, which, for example, would occur if you send a message to an object that cannot respond to it.
  • You can also use introspection to help locate an object in the inheritance hierarchy, which would give you information about the object’s capabilities.
3. NSObject gives us Memory management methods :

     Methods like alloc, dealloc, retain, copy etc.

4. NSObject gives us Method Invocation methods.



As it is giving us all these, we call NSObject as the root class of all Objective C classes.