Tuesday, November 27, 2012

selector objective C

Selector is another feature which supports ObjectiveC. A Selector is same as function pointers in C. So Using selector, we will get the reference of the method, later we will use that reference for calling the method. A SEL is a special type which holds a pointer to the symbolic name of a method.

@selector is a directive to get the pointer for the method. After getting the reference, using below two methods we can do the operations.
  • respondsToSelector : This used to check whether the method definition is available or not. It does not look for the declaration of the method, it just checks in implementation file for the method definition.
  • performSelector : This is used to call the method.
Syntax for the selector:
//both are same , any one is fine
SEL selectorName= @selector(methodName);
SEL selectorName = NSSelectorFromString(@”methodName");

Using Selectors to Call Methods: Below is the example for the usage of the selector and its methods.
//This is in .h file
@interface selectorDemo : NSObject
-(void) display;
-(void) output;
@end

//below is in .m file
@implementation selectorDemo
-(void) display
{
    NSLog(@"this is display function");
}
-(void) output
{
    NSLog(@"this is output function");
}
@end

//this is in main.m
int main(int argc, const char * argv[])
{

    selectorDemo *obj = [[selectorDemo alloc] init];
    // This selector declaration for display method
    SEL selDisplay = @selector(display);

    //checking whether method definition is available or not
    if([obj respondsToSelector:selDisplay])
    {
        //calling method
        [obj performSelector:selDisplay];
    }
    
    //another syntax for the selector declaration
    SEL selOutput = NSSelectorFromString(@"output");
    //calling method
    [obj performSelector:selOutput];
    
    return 0;
}

Friday, November 23, 2012

private method objective C


In objectiveC, privilege levels are allowed for  only data variables and not for methods. So public, private and protect  access specifiers are valid for only data variables. But there is a feature called Category which is used for declaring private methods in objectiveC.

Using category we can implement private methods. But we need to declare the methods in .m file and not in .h file. So declaration and definition will be in the same source file.

Syntax for the private method:
//need to add both in .m file
@interface className (categoryName)
//new methods
@end

@implementation className (categoryName)
//new method definitions
@end

Example for private method: In this example, we add one private method to the NSObject class using category and its name is display which is enclosed in the braces. 
@interface NSObject (display)
-(void) privateDisplay;
@end

@implementation NSObject (display)
-(void) privateDisplay
{
    printf("This is private display\n");
}
@end

//This class is declared in the .h file 
//and inherited from NSObject
@implementation categoryClass
@end


Wednesday, November 21, 2012

objective c categories

Categories is another good feature in ObjectiveC. A category  is used to add the new methods to the existing class, even if you don't have source code of the class. Category only adds methods and not variables. The basic difference between category and extending the class is that, in extending the class you can additional methods and variables. But in category only methods are allowed.

A category is also used to declare the private methods. ObjectiveC provides security to only data variables and not for methods. So we can have public, protect and private access privileges to only data.  Using category we can implement private methods. But we need to declare the methods in .m file and not in .h file.

Key points on Category:
  • Used to add the new methods to the exiting class and not variables
  • Used to create the private methods in objectiveC
  • No keyword is used for declaring category. Only enclosed in braces(see the syntax).
  • You can take as many catefories as you want, but they should be unique.
  
Syntax for the Category:  There is no keyword for the declaration of the category. We need to enclose in the braces '(' and ')';
//.h file
@interface className (categoryName)
//new methods
@end
//.m file
@implementation className (categoryName)
//new method definitions
@end

Example for adding methods: In this example we add display method to the NSObject. We we have written two implementations, one is for NSObject new method and one is for new class.

// this is .h file
@interface NSObject (print)
-(void) display;
@end

@interface categoryClass : NSObject

@end

//this is in .m file

@implementation NSObject (print)
-(void) display
{
    NSLog(@"this is display function");
}
@end

@implementation categoryClass
@end

int main()
{
    categoryClass *obj = [[categoryClass alloc] init];
    [obj display];
}

Monday, November 19, 2012

objective c @class

In Objective C @class is used for forward declaration. It tells the compiler that there’s a class of that name. we can use it in the interface declarations.

Lets see the sample code below.
@interface example : NSObject
{
    //compiler dont know where this class located
    forwardDemo *obj;
}
@end

@interface forwardDemo : NSObject
{
    //data
}
@end


In the above sample code, we have a interface  example, data variable to that interface is object of another interface forwardDemo.  But example interface dont know the declaration/existance of the forwardDemo interface, this is because example is declared before forwardDemo interface. To overcome this problem, we need to use the forward declaration. In objective C which is achieved by using @class keyword. Solution for the above is given below.
//forward declaration
@class forwardDemo;
@interface example : NSObject
{
    forwardDemo *obj;
}
@end

@interface forwardDemo : NSObject
{
    //data
}
@end


Saturday, November 17, 2012

objective c protocol

Objective-C doesn't support multiple inheritance. So each class should have only one parent class. It should not have multiple parent classes for the derived class. But Objective-C supports a feature called protocol to implement multiple inheritance.

A protocol  is a list of method declarations. And if you want use those methods , you need to write the implementation for those methods.

A protocol feature in objective-C is similar to interface in Java and pure virtual function in C++.

Syntax of the protocol declaration: you need to enclose the protocol in < and > when using it.
@protocol protocolName 
//new methods
@end

//class name and protocol names separated by spaces
@interface className : parentClass <protocolName>
//class methods
@end



Example for the protocol in Objective-C:
// these are in .h file
@protocol player 
-(void) bowling;
-(void) batting;
-(void) fielding;
@end

@interface cricketPlayer : NSObject <player>
-(void) display;
@end


// this is in .m file
@implementation cricketPlayer
-(void) display
{
    NSLog(@"this is display function");
}
-(void)batting
{
    NSLog(@"this is batting");
}
-(void)bowling
{
    NSLog(@"this is bowling");
}

-(void)fielding
{
    NSLog(@"this is fielding");
}
@end


int main(int argc, const char * argv[])
{
    
    cricketPlayer *obj = [[cricketPlayer alloc] init];
    [obj display];
    [obj batting];
    [obj fielding];
    return 0;
}

From the above example protocol with name player have three methods batting, bowling and fielding. We have created a new class called cricketPlayer whos parent class is NSObject and it uses the player protocol.  So cricketPlayer's object is able to use all the methods which are available in the protocol. So now object has the properties of NSObject and protocol methods  as well.

This way you can implement multiple inheritance using protocol.

Friday, November 16, 2012

how to know the end of the file in action script!!!


There are two ways to find the end of the file using action script for the flv files.
  1. Using meta data (which we will get by getting meta event onMetaData)
  2. Using netStatus code "NetStream.Play.Stop"
Using onMetaData: When this event occurs, we need to take the duration of the file by using mdata.duration, which gives the duration of the file. After getting the duration of the file, we need to compare with the buffer length of the file while playing. Actually playing flv file in action script is, taking the fixed buffer length and play that buffer and after completing that buffer again take buffer and play that buffer, this process will continue till it reaches empty. So if the file is empty, buffer length reaches duration of the file or more. For us this condition is important, for checking end of the file, we can check this condition as shown in the sample code below.
 

Getting duration of the file:
public function onMetaEvent(mdata:Object):void
{
      //taking the duraiton time for looping
      lastPosition = mdata.duration;
}

Finding the end of the file:
public function netStatus(item:Object):void
{
   //Unpause.Notify code will be generated whenever buffer fills with data
   if (item.info.code == "NetStream.Unpause.Notify")
   {
      if (Math.floor(stream.bufferLength) >= Math.floor(lastPosition))
      {
         //buffer length reaches end of the file
      }
   }
}

Using netStatus code "NetStream.Play.Stop" : Here we need to check for the NetStream status code Play.Stop. as shown in the below sample code.

public function netStatus(item:Object):void
{
   if (item.info.code == "NetStream.Play.Stop")
   {
      //reaches end of the file
   }

}

For more NetStream status codes click here.

Wednesday, November 7, 2012

Error #2044: Unhandled NetStatusEvent

Recently we worked on the simple application called face detection using actionscript. While doing this application, we faced some common problems, we are sharing here.

Scenario: When the application did not find any face in front of camera, it needs start playing some flv file. For this we created the flv player and added the flv file to the player. Below is the code for that.
nc=new NetConnection();
nc.connect(null);
ns = new NetStream(nc);
vid = new Video(320,240);
                       
addChild(vid);
client = new Object();
ns.client = client;
client.onMetaData = nsMetaDataCallback;

vid.attachNetStream( ns );                       
//This file we are going to play in the player
ns.play( "trailer.flv" );


When we try to compile the code, we got the below error.

Error #2044: Unhandled NetStatusEvent:. level=error, code=NetStream.Play.StreamNotFound

The reason for the above problem is, file path is not proper. Check for the file name or path for the given flv file. we have given tralier.flv instead of trailer.flv

Possible error codes are :
  • NetStream.Buffer.Empty
  • NetStream.Buffer.Full
  • NetStream.Buffer.Flush
  • NetStream.Play.Start
  • NetStream.Play.Stop
  • NetStream.Seek.InvalidTime
  • NetStream.Seek.Notify      



Monday, November 5, 2012

C Program for Rearranging linked list first odd next even numbers

Below is the C program for rearranging the linked list (not copying the elements), in such a way that, first odd elements next even elements should come as shown below. I faced this question in Amazon Interview first round. So Sharing the program here.

Input list:    1 2 3 4 5 6 7 8 9 10
OutputList: 1 3 5 7 9 2 4 6 8 10

#include<stdio.h>
#include<stdlib.h>
 
//linked list structure
struct node
{
 int info;
 struct node *next;
};
 
//making typdef so we can use Node instead of 'struct node'
typedef struct node Node;

//rearranging the linked list in such a way that odd no.s first 
//and then even no.

Node* oddEven(Node* h)
{
        Node* tempNode = h;
        Node* oddEnd = NULL,*oddHead = NULL;
        Node* evenHead = NULL, *evenEnd = NULL;

        while( tempNode != NULL)
        {
                if(!(tempNode->info%2))
                {
                        if(evenHead == NULL)
                                evenHead = tempNode;
                        else
                                evenEnd->next = tempNode;
                        evenEnd = tempNode;
                }
                else
                {
                        if(oddHead == NULL)
                                oddHead = tempNode;
                        else
                                oddEnd->next = tempNode;
                        oddEnd = tempNode;
                }
                tempNode = tempNode->next;
        }
        h = oddHead;
        oddEnd->next = evenHead;
        evenEnd->next = NULL;
        return h;
}
 
//inserting node or creating the list or adding the element @ end
Node* insert(Node *h, int info)
{
 Node *tempHead=h;
 Node *newNode = (Node*)malloc(sizeof(Node));
 newNode->info = info;
 newNode->next = NULL;
 if(tempHead == NULL) // if the list has zero elements. make new node as a head
 {
  h=newNode;
 }
 else if(tempHead->next==NULL)  // if the list is having only one node
 {
  tempHead->next = newNode;
 }
 else
 {
  Node *tempNode = h;
  while(tempNode->next != NULL)  // if the list has more than one node, so moving to the last node
  {
   tempNode = tempNode->next;
  }
  tempNode->next = newNode; // appending the new node at the end
 }
 return h;
}
 

/*****************************************************************************
for displaying the nodes in the list
*****************************************************************************/
void display(Node *h)
{
 Node *temp = h;
 while (temp->next!=NULL)
 {
  printf("%d->",temp->info);
  temp = temp->next;
 }
 printf("%d\n",temp->info);
}
 
int main()
{
 Node *head = NULL;
 int i,n,element,choice,pos,size;
 for (i=1;i<20;i++)
 {
  head = insert(head,i);
 }
 display(head);
 head=oddEven(head);
 display(head);
}

Output:

Input Linked List:
1->2->3->4->5->6->7->8->9->10->11->12->13->14->15->16->17->18->19

Resulted List:
1->3->5->7->9->11->13->15->17->19->2->4->6->8->10->12->14->16->18

Friday, November 2, 2012

Call back Functions issue !!!


Adding a call back routine: 

- It is very Simple to create call back reference to a given function , But care must be taken while defining the function body -As few compilers (old compilers though !!! ) may not give you a warning also if your function definition is different from the callback declaration and its invoking. Let us see an example which illustrates the problem.

#include<stdio.h>

//pointer to the function
int (*ptr_2_func)(int,int);
int test_my_function (int a, int b,int c)
//int test_my_function (int a, int b)  - This should be the function definition
{
  printf ("values of a is %d b is %d c is %d\n",a,b,c);
// printf ("values of a is %d b is %d \n",a,b);
 return 0;
}
int main()
{
  int ret = 0;
  ptr_2_func = test_my_function;
  ret = ptr_2_func(10,30);
  return 0;

}
" If we ignore the warning messages( in case your compiler is intelligent enough !!! ) , which most of the rookie programmers tend to - your program might end up crashing at some point of time if not immediate .
So its always better to make sure that your function pointer match  the function prototype.


Tuesday, October 30, 2012

implementing doubly linked list using single pointer


The problem with single linked list is that, we cant back traverse, only forward traversal is allowed because current node contains the address of the next node.  To traverse back wards we need another pointer to store the previous address and that concept is called doubly linked list.

We can implement back traversal by storing previous and next node address in the single pointer. For this we need to use the concept of XOR operation.

XOR Operations: let’s see the beauty of XOR operation.

If you perform XOR operation on any two input values, you will get some result. And if you perform again XOR operation with result and any one of the two input values, you will get other input value. We are going to use this logic to store the prev and next node values. See the example below.

  a ^ b = c
  c ^ b = a
  c ^ a = b

So while creating the linked list, we need to perform XOR operation to get the next node value.  The key point in this process is, we need to maintain the prev node value to make the XOR operation.

Creating and storing the next pointer value:  The value which we are going to store in the next pointer is the XOR operation of prev and new nodes. So next pointer of the node should not points to the next node, instead of that, its having some value which is a combination of prev and next nodes as shown in the picture. For complete code click here.



If the list contains single node, as prev pointer value is initially NULL, so there wont be any problem.

Forward traversing: to move the pointer from current node to next node, the sample code is given below. For complete C implementation click here.

current = current->next ^ prev

Before Operation:
After Operation:

After executing above statement, the current node moves to the next node as shown below.

Backward traversal:  Assume that below is the scenario and we are at current node and we know the address of temp, so to get the prev node of the current node, the sample code is below. For complete C code click here.

while(temp!=h)
 {
   printf("%d->",temp->info);
   prev = prev->next ^ temp;
   temp = tempPrev;
   tempPrev = prev;
 }

Before operation:

After operation:

In this way, we  need to do the operations to get the prev node and next node addresses. And there are more statements to maintain prev and next node pointers. Click here for the complete working C Implementation.

Note: XOR operation can be performed only on integer or char data type. And XOR is not allowed on structure as it is user defined data type. To perform the XOR operation, we need to type cast it to long int.


Popular Posts