如何编写一个合适的单例BOOL函数

时间:2013-03-04 18:07:49

标签: ios objective-c singleton asihttprequest

我正在使用ASIHTTPRequest检查用户是否已登录,并在登录成功时尝试返回布尔值

问题:当我请求布尔值时,它总是返回0,然后几秒钟后ASIHTTPRequest完成其请求并更新布尔值。

我想要的是什么:在所有请求完成后获取布尔值。我认为正确的方法是编写一个布尔函数并检索asihhtp请求的结果?

单身人士

@interface CloudConnection : NSObject
{
    BOOL isUserLoggedIN;
}
@property BOOL isUserLoggedIN;
+ (CloudConnection  *)sharedInstance;
@end

+ (CloudConnection *)sharedInstance
{
    static CloudConnection *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[CloudConnection alloc] init];
        // Do any other initialisation stuff here

    });
    return sharedInstance;
}

- (id)init {
    if (self = [super init]) {
        //send login request
        [self sendLoginRequest];
    }
    return self;
}
-(void) sendLoginRequest{ .....}
- (void)requestFinished:(ASIHTTPRequest *)request
{ else if (request.responseStatusCode == 202) {
        //parse  json data
        NSLog(@"Login Succesfull");
        _isUserLoggedIN=YES;
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request{}

在VC中:

CloudConnection *sharedInstance=[CloudConnection  sharedInstance];
 NSLog(@"is logged in init %hhd",sharedInstance.isUserLoggedIN);
[self performSelector:@selector( checkLoginAfterFiveSeconds) withObject:nil afterDelay:5.0];

-(void) checkLoginAfterFiveSeconds
{

    CloudConnection *sharedInstance=[CloudConnection  sharedInstance];
    NSLog(@"is logged in init %hhd",sharedInstance.isUserLoggedIN);
}

的NSLog:

is logged in init 0
Login Succesfull`
is logged in init 1 //after 5 secs

2 个答案:

答案 0 :(得分:0)

如果你按照你的建议行事,它会阻止调用线程。并且你永远不会想要一个等待网络流量的线程,尤其不是主/ ui线程

使它成为一个void函数并使其调用completionHandler或...一旦结果可以直接计算就发送NSNotification! :)

答案 1 :(得分:0)

是的你是对的:) 在您的请求完成块中调用此方法:

[self loginResult:result];

-(void)loginResult:(BOOL)result
{
    if(result == TRUE)
    {
        NSLog(@"Login successfully now call any method or do what ever you want");
    }
    else
    {
        NSLog(@"Login unsuccessfull");
    }
}