He encontrado ese patrón de singleton en la red. Me parece que tiene muchas cosas que se pueden optimizar.Objective-C - ¿Optimizar este patrón singleton?
-In sharedMySingleton
método, no es necesario llamar a retener? No estoy seguro ...
-Si no, ¿por qué hay una retención en allocWithZone
?
-cual es el uso de @synchronized
. Los NSAssert hacen pensar que se puede llamar al bloque muchas veces, por lo que, en caso afirmativo, debería haber más código para liberar la memoria anterior, o salir del bloque claramente sin solo insertar NSA, y en caso negativo, ¿por qué hay NSAssert?
-la cadena comprendida entre sharedMySingleton
y alloc
parece extraña. Yo escribí mi mismo algo así como:
+(MySingleton*)sharedMySingleton
{
@synchronized([MySingleton class])
{
if (_sharedMySingleton == nil) _sharedMySingleton = [[self alloc] init];
return _sharedMySingleton;
}
return nil;
}
+(id)alloc
{
@synchronized([MySingleton class])
{
return [super alloc];
}
return nil;
}
patrón Singleton
#import "MySingleton.h"
@implementation MySingleton
// ##########################################################################################################
// ######################################## SINGLETON PART ##################################################
// ##########################################################################################################
static MySingleton* _sharedMySingleton = nil;
// =================================================================================================
+(MySingleton*)sharedMySingleton
// =================================================================================================
{
@synchronized([MySingleton class])
{
if (_sharedMySingleton == nil) [[self alloc] init];
return _sharedMySingleton;
}
return nil;
}
// =================================================================================================
+(id)alloc
// =================================================================================================
{
@synchronized([MySingleton class])
{
NSAssert(_sharedMySingleton == nil, @"Attempted to allocate a second instance of a singleton.");
_sharedMySingleton = [super alloc];
return _sharedMySingleton;
}
return nil;
}
+ (id)allocWithZone:(NSZone *)zone { return [[self sharedMySingleton] retain]; }
- (id)copyWithZone:(NSZone *)zone { return self; }
- (id)retain { return self; }
- (NSUInteger)retainCount { return NSUIntegerMax; /* denotes an object that cannot be released */}
- (oneway void)release { /* do nothing */ }
- (id)autorelease { return self; }
// ##########################################################################################################
// ##########################################################################################################
// ##########################################################################################################
// =================================================================================================
-(id)init
// =================================================================================================
{
if (!(self = [super init])) return nil;
return self;
}
// =================================================================================================
-(void) dealloc
// =================================================================================================
{
[super dealloc];
}
// =================================================================================================
-(void)test
// =================================================================================================
{
NSLog(@"Hello World!");
}
@end
¿Qué pasa con los otros métodos: retener, retener cuenta, liberar, copiarWithZone, ...? ¿Por qué estás hablando de versiones "modernas"? ¿Qué quieres decir con moderno? ¿Alguna idea de por qué Apple no actualizó su fragmento singleton con este tipo de código? – Oliver
Por moderno, quiero decir desde la introducción de GCD. No debe anular estos métodos. El único código de muestra que muestra una anulación de estos está aquí: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html Como se observa, esta es una implementación * strict * de singleton, que el texto anterior explica generalmente no es necesario. Abrí un doc case para mejorar esta documentación, ya que confunde a muchos desarrolladores. Mike Ash tiene una buena publicación sobre esto: http://www.mikeash.com/pyblog/friday-qa-2009-10-02-care-and-feeding-of-singletons.html –
¿Cuál es el equivalente a 10.6 en términos de iOS? – Oliver