Category Archives: Formacion

Capítulo I: Objective-C. Lección 1: Conoce la sintaxis.

¿Qué es Objective-C?

En la teoría Objective-C es una extensión orientada a objetos (POO) de la sintaxis de C, no se trata en sí de otro lenguaje, sino que se trata del bien conocido y viejo amigo C, solo que se le han agregado muchas cosas interesantes y útiles. Si bien en un principio es cierto, la realidad es que debes acostumbrarte a las características de Objective-C.


La definición de la clase se realiza en el archivo de cabecera, que debe terminar en “.h”, como en C normal.

//MiClase.h #import typedef enum { rojo=0,azul,verde }Color; @interface MiClase : NSObject { /* Comentario estilo C: definición de miembros */  int enteroA;  int enteroB; } //Definición de métodos -(int) getEnteroA: -(void) setEnteroA:(int) _entero; -(int) getEnteroB: -(void) setEnteroB:(int) _entero; -(int) multiplicaEnteros; +(char*) nombreDeColor:(Color) color; @end

¿Cómo se ve una clase en Objective-C? Para alguien que viene de Java o C/C++ se ve familiar, pero a la vez, se desconocen varias cosas, la primera, definición de clases:

  • Se comienza con la palabra reservada @interface.
  • NSObject: Es la abreviación de NeXTStep Object, es la clase mas abstracta que hay, todas las clases deben heredar de otra clase o de NSObject.
  • La herencia se indica con Clase : ClasePadre, como en MiClase : NSObject.
  • Las variables de instancia se declaran entre las llaves de @interface Clase : NSObject { … }.
  • El acceso por defecto es protected.
  • Después de los miembros de la clase se especifican los métodos, que tienen la forma: alcance (tipoDeRetorno) nombreDeMetodo:(tipoParametro1) parametro1:
  • El alcance de un método se especifica con un signo menos: – para métodos de instancia; y un signo más + para metodos de clase.
  • La definición termina con @end.


La implementación de la clase se escribirá en un archivo con terminación “.m”:

//MiClase.m #import “MiClase.h” @implementation MiClase -(int) getEnteroA {  return enteroA; } -(void) setEnteroA:(int) _entero { enteroA=_entero; } -(int) getEnteroB {  return enteroB; } -(void) setEnteroB:(int) _entero { enteroB=_entero; } -(int) multiplicaEnteros {  return enteroA*enteroB; } +(char*) nombreDeColor:(Color) color {  switch(color) {   case azul:    return “Azul”;   break;   case rojo:    return “Rojo”;   break;   case verde:    return “Verde”;   break;  } return “Color Desconocido”; } @end

La implementación de la clase

  • Se comienza con @implementation NombreDeClase.
  • La definición de los métodos se realiza de manera similar a como se hizo la definición en la cabecera de la clase.
  • Se termina con la palabra reservada @end.

Usando la clase.

Como ya mencioné, Objective-C es una extensión de C, y sabemos que todo programa de C, debe tener una función main:

#import #import “MiClase.h” int main( int argc, const char *argv[] ) {     MiClase *instancia = [[MiClase alloc] init];     //Debemos especificar los valores:     [instancia setEnteroA:1];     [instancia setEnteroB:12];     //llamamos a los métodos de la instancia que devuelven valores     printf(“%d por %d es igual a %d”,[instancia getEnteroA],           [instancia getEnteroB], [instancia multiplicaEnteros] );     //tenemos que liberar la memoria cuando ya no necesitamos la instancia     [instancia release];     //Pero podemos llamar a los métodos de la clase:     printf(“%s”,[MiClase nombreDeColor:rojo]);     return 0; }
  • Las llamadas a métodos de una clase, de una manera equivalente a C++ instancia->metodo() se hace en la forma [instancia metodo];
  • Se puede hacer llamadas anidadas: [[instancia metodoQueDevuelveOtroObjeto] llamadaAMetodoDelObjetoDevuelto] .sería el equivalente a lo siguiente en C++: (instancia->metodoQueDevuelveOtroObjeto())->llamadaAMetodoDelObjetoDevuelto();
  • Para Crear instancias de una clase se usa MiClase *instancia=[[MiClase alloc] init];
  • A diferencia de C++, Objective-C siempre utiliza apuntadores para objetos de las clases.
  • Para obtener la instancia de la clase la llamada al Método alloc, es como usar malloc en c, solo reserva la memoria para la instancia.
  • La llamada al método init, efectúa al inicialización de la instancia, como un constructor.
  • Usualmente se efectua en una sola línea para crear e inicializar el objeto: MiClase *instancia=[[MiClase alloc] init];
  • Al igual que en las otras variantes de C, debes liberar la memoria obtenida con alloc, llamando al método release, que es heredado de NSObject.

Bien, eso es todo por hoy. Saludos.


How to Integrate iAd for OS3.2+ and Admob as Backup

I am impressed with iAd revenue given by Apple. It really surprises me. So I end up putting iAds for most of my free apps. Though, I’d like the app to be downloaded by OS3.2 users as well (wider user base). So, upon searching, I found the tutorial from Ray Wenderlich. It totally works! If your app is ran on 3.2, it will not cause a crash using this way. iAd is simply not instantiated in OS3.2.


This post is not really a step by step tutorial for the codings, but more of an explanation of what needs to be done in order to have iAd integrated in your app, with Admob as backup ad in OS3.2 and when iAd fails. Please read this post carefully. With the downloadable full project source code sample, you should be able to figure this out easily.

1. To get the Admob SDK, you need to be registered to Admob and add a new Site/Apps. Key in your app URL, and soon the Admob Publisher Code will be given and you can then download the Admob SDK built specifically for your app (basically the SDK will be pre-filled with your publisher code).

2. All you need to do is then copy 2 folders – Admob and TouchJSON into your app folder in Finder. Then drag these 2 folders in your XCode Project group. Then you need to add 5 Frameworks to your project. They are MediaPlayer, CoreGraphics, AudioToolBox, MessageUI, and QuartzCore.

3. For iAd, you need to add and weaklink the iAd.framework. Click on Targets->”App name” and get the info of it. Then go to General tab and underneath there is a list of frameworks. On the right side, there is a column called “Type”. Click on the value “Required” and change to “Weak”.

4. Now for the required codes to declare Admob and iAd. In .h of your viewcontroller, declare as below (read the comments in code below for more details):

#import “AdMobDelegateProtocol.h”
@class AdMobView;

@interface iAdMobViewController : UIViewController {
id _myAD; // we are declaring as id because OS3.2 won’t know the existance of ADBannerView
AdMobView *adMobAd;
NSTimer *admobTimer;
IBOutlet UIButton *exampleBtn; // just to simulate repositioning objects

@property (nonatomic, retain) NSTimer *admobTimer;
@property (nonatomic, retain) id myAD;
@property (nonatomic, retain) UIButton *exampleBtn;

-(void)createAdBannerView; // method to create iAd banner view
-(void)callAdmob; //method to create Admob view

// methods to show or hide iAd view upon receiving ad or failing to receive ad.

// methods to show or hide Admob view upon receiving ad or failing to receive ad.


Then in .m file, we need to include a header file for Admob only.

#import “AdMobView.h”

Most of the code above is pretty straight forward. Though NSTimer deserves a little explanation. Admob works a little different than iAd. For iAd, once we create the BannerView, retained it, then iOS will continue to call for adverts from Apple server every 30seconds (edit: only test iAd in SDK 4.0 is called every 30sec, actual iAd refresh is called every 3 minutes). It is done automatically. But for Admob, the SDK does not call for new ads automatically. For Admob, the ad will be called once everytime we create/alloc an AdMobView. If you see in the AdMob delegates, there is one function called requestFreshAd, though this just refresh the ad inside the view with new one WITHOUT calling the didReceiveAd delegate!

Our goal in this project is to make iAd the master ad server, and admob the secondary ad filler. So, in OS4.0, we instantiate iAd once, so the iOS will continue to send ad requests every 30 seconds. So we set the iAd to show if the ad is received, and set to create and show Admob ad if iAd fails. This cycle will continue forever. So we will be having iAd and Admob continuously showing.

Though, in OS3.2, iAd NEVER gets instantiate. So the iAd didFailToReceiveAd delegate will never get called, and that means Admob ad will never be instantiated as well! So we need to trigger the creating of Admob ad calling manually. And that’s where admobTimer comes in the picture.

Testing the project can be painstaking at times. Because since we make iAd the master, and iAd Test ads fillrate is like 99%, it will take a while for Admob Test ad to appear. During running the project in simulator, monitor it together with Console so that you can see the logs every 30 seconds. Test the app with iPad Simulator 3.2 too, and it should not crash, and you should only see Admob ads in the iPad Sim3.2.

There are a few more things that is important in setting up the Admob Delegate functions.

1. The Publisher ID delegate. Key in YOUR Publisher ID in that string placeholder. (in your .m file)

– (NSString *)publisherIdForAd:(AdMobView *)adView {
return @”your admob publisher id here”;

2. To get the test Ads for Admob, put this delegate:

– (NSArray *)testDevices {
return [NSArray arrayWithObjects:

3. To get test ads in your devices, just add your 40digits device ID as NSString into the array in the above delegate function. If you have more devices, just continue to add them to the array.

– (NSArray *)testDevices {
return [NSArray arrayWithObjects:
@”your 40digit device ID here”

4. To get test ads in iAd, you don’t need to do anything in Simulator. Even if you haven’t added a new version with iAd enabled in iTunesConnect, you can still receive test ads in the iAds in simulator or device.


You might also like:
Simple Ball Animation
How To Do: Slide to Unlock
Creating Flashing Custom Button

Why are my iAds not displaying in the iPhone Simulator in iOS 4.1?

iAd is for iOS 4.0 and above, so 4.1 should be fine.

Did you miss one of the step below…

  • Add iAd.framework to your project
  • #import <iAd/iAd.h> in your view controller .h file
  • Drag and drop iAdBannerView to your interface
  • Link adView variable and delegate using the interface builder
  • Implement the delegate bannerViewDidLoadAd that show the ad
  • Implement the delegate didFailToReceiveAdWithError that hide the ad

You can see the code below and adapt to your own need…

// RootView.h

#import <UIKit/UIKit.h>
#import <iAd/iAd.h>

@interface RootView : UIViewController {
    BOOL bannerIsVisible;
    ADBannerView *adView;

@property (nonatomic) BOOL bannerIsVisible;
@property (nonatomic, retain) IBOutlet ADBannerView *adView;

// RootView.m

#pragma mark -
#pragma mark iAd Banner

- (void)bannerViewDidLoadAd:(ADBannerView *)banner {

    YourAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    UINavigationController *navigationController = (UINavigationController *)[appDelegate navigationController];

    if (self.bannerIsVisible == NO) {
        banner.frame = CGRectOffset(banner.frame, 0, -banner.frame.size.height);
        [navigationController view].frame = CGRectMake(0, 0, 320, 410);
        self.bannerIsVisible = YES;

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error {

    YourAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    UINavigationController *navigationController = (UINavigationController *)[appDelegate navigationController];

    if (self.bannerIsVisible) {
        banner.frame = CGRectOffset(banner.frame, 0, banner.frame.size.height);
        [navigationController view].frame = CGRectMake(0, 0, 320, 460);
        self.bannerIsVisible = NO;
1 2 3 4 6