sábado, 10 de diciembre de 2011

Basic language syntax II

It once learned as a class consists in Objective-C, next thing to learn is functions and methods

Functions and methods

As explained above, a class in Objective-C had an interface (. H) and implementation (. M).
Therefore the interface must list all methods and functions, an example of method could be:

  1. //Declare...
  2. -(void)addFriendWithName:(NSString *)name;

In the implementation ...

  1. -(void)addFriendWithName:(NSString *)
  2. {
  3.        //Code for our method
  4. }

We can see that there is a method start (-) to indicate that this method will be used
when you instantiate the class that contains it.

For example we could use the class importing the header (interface), in this case we could call it "Friend".

Then it would be something like:

  1. //Import header file
  2. #import "Friend.h"

And when we call it, we must instantiate it like

  1. Friend *objFriend = [[[Friend alloc] init] autorelease];
  2. [objFriend addFriendWithName:@"Nicolas"];

In this way we create a pointer to memory using alloc, initialize and invoke autorelease to tell the compiler to add the pointer to a release stack. This means that when not needed, this object will be removed automatically.
Recall that in Objective-C, we use memory management, so the objects must be freed as we don't need them anymore.

We could also start the method with a (+), which means it will be a class method or function. You can call directly without being allocated, either instantiated.
So when we write the call...

  1. //Call method
  2. [Friend addFriendWithName:@"Nicolas"];

If we write a method that contains more than one parameter:

  1. //More parameters!
  2. -(void)addFriendWithName:(NSString *)name withEmail:(NSString *)email;

No hay comentarios:

Publicar un comentario