项目后对objective-c 单例理解?#define DEFINE_SHARED_INSTANCE_USING_BLOCK(block) \static dispatch_onc
项目后对objective-c 单例理解
?
#define DEFINE_SHARED_INSTANCE_USING_BLOCK(block) \static dispatch_once_t pred = 0; \__strong static id _sharedObject = nil; \dispatch_once(&pred, ^{ \_sharedObject = block(); \}); \return _sharedObject; \
?
?
?
?
?
?
?
?
?
1 楼 啸笑天 12 小时前 Just wanted to say thanks. I too created a macro on the same premise to be a bit more generic:
/*!
* @function Singleton GCD Macro
*/
#ifndef SINGLETON_GCD
#define SINGLETON_GCD(classname) \
\
+ (classname *)shared##classname { \
\
static dispatch_once_t pred; \
__strong static classname * shared##classname = nil;\
dispatch_once( &pred, ^{ \
shared##classname = [[self alloc] init]; }); \
return shared##classname; \
}
#endif
This assumes the init is a standard init.
Then to implement in the .h
@interface MyClass : NSObject
+ (MyClass *) sharedMyClass;
@end
and in the .m
#import "MyClass.h"
@implementation MyClass
SINGLETON_GCD(MyClass);
- (id) init {
if ( (self = [super init]) ) {
// Initialization code here.
}
return self;
}
@end
I assume that __strong is not necessary if this is a Mac OS X app?
Also, allocWithZone can be ignored when using Garbage Collection?
Thanks again... 2 楼 啸笑天 12 小时前 //
// SynthesizeSingleton.h
// CocoaWithLove
//
// Created by Matt Gallagher on 20/10/08.
// Copyright 2009 Matt Gallagher. All rights reserved.
//
// Permission is given to use this source code file without charge in any
// project, commercial or otherwise, entirely at your risk, with the condition
// that any redistribution (in part or whole) of source code must retain
// this copyright and permission notice. Attribution in compiled projects is
// appreciated but not required.
//
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
\
static classname *shared##classname = nil; \
\
+ (classname *)shared##classname \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [[self alloc] init]; \
} \
} \
\
return shared##classname; \
} \
\
+ (id)allocWithZone:(NSZone *)zone \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [super allocWithZone:zone]; \
return shared##classname; \
} \
} \
\
return nil; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return self; \
} \
\
- (id)retain \
{ \
return self; \
} \
\
- (NSUInteger)retainCount \
{ \
return NSUIntegerMax; \
} \
\
- (void)release \
{ \
} \
\
- (id)autorelease \
{ \
return self; \
}