iPhone: Create Singleton instance

A continuación veremos como crear una clase singleton en objective-c.

Un singleton es una clase con una única instancia. Puede servirnos para guardar variables globales de la aplicación.

MySingletonInstance.h

#import <Foundation/Foundation.h>
@interface MySingletonInstance : NSObject{
}
@property (nonatomic,retain) NSString *myString;
@property (nonatomic,retain) NSMutableArray *myArray;
+ (MySingletonInstance *) instance;
@end

MySingletonInstance.m

#import "MySharedSingleton.h"
@implementation MySharedSingleton
@synthesize myArray, myString;

static MySingletonInstance *sharedSingletonInstance = nil;

+ (FilterParams *) instance {
    @synchronized(self) {
        if(sharedSingletonInstance == nil) sharedSingletonInstance = [[self alloc] init];
    }
    return sharedSingletonInstance;
}

+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if(sharedSingletonInstance == nil) {
            sharedSingletonInstance = [super allocWithZone:zone];
            return sharedSingletonInstance;
        }
    }
    return nil;
}

- (id) copyWithZone:(NSZone *)zone {
    return self;
}

- (id) retain {
    return self;
}

- (unsigned) retainCount {
    return UINT_MAX;
}

- (void) dealloc {
    [super dealloc];
    [myArray release];
    [myString release];
}

- (id) autorelease {
    return self;
}

Como llamar al singleton desde otra clase

MySingletonInstance *msi = [MySingletonInstance instance];
msi.myArray = self.myOtherArray;
msi.myString = self.myOtherString;

iPhone: NSLog frame

Muchas veces necesitamos pintar un frame de un objeto, ya sea un button, un view, un scrollview, etc…

Para debugarlo existe la función NSStringFromCGRect, que nos devuelve el frame del objeto que le pasamos como un string.

Por ejemplo, para pintar el frame de un view haríamos:

iPhone: Sort NSMutableArray

Aquí vemos como podemos ordenar un NSMutableArray en función de uno de los atributos de los elementos