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;
Aun no hay comentarios.