我的单例访问器方法通常是以下的一些变体:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
Run Code Online (Sandbox Code Playgroud)
我可以做些什么来改善这个?
我试图通过其他以及Apple的例子.我迷路了.
我有一个单例类,用于处理我的用户登录(挑战Web服务器等).
我想创建一个我可以调用的块,传入用户名/密码.该块将执行Web服务调用,如果成功则返回.
这是我到目前为止工作的目标:
我的单例类看起来像这样:
.H
typedef void (^AMLoginBlock)(NSString *userName, NSString *password);
@interface AuthManager : NSObject
+ (id)sharedManager;
+ (bool)loginUserWithBlock:(AMLoginBlock)block;
@end
Run Code Online (Sandbox Code Playgroud)
.M
@implementation AuthManager
+ (id)sharedManager
{
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init]; // or some other init method
});
return _sharedObject;
}
+ (bool)loginUserWithBlock:(AMLoginBlock)block {
NSLog(@"im printing from AM");
return true;
}
@end
Run Code Online (Sandbox Code Playgroud)
然后我调用这样的方法:
bool rtn = [AuthManager loginUserWithBlock:^(NSString *userName, NSString *password) {
NSLog(@"im here in the …Run Code Online (Sandbox Code Playgroud)