存储和检索nsuserdefaults中的值时发生冲突

时间:2016-04-23 09:04:48

标签: ios nsuserdefaults

我有两个文件,APIRequest.mLoginController.m

APIRequest.m文件有一个方法receiveLoginData,其中包含以下代码。将从服务器接收状态代码。如果凭据都是正确的,则状态代码将为1,否则为0.我将其保存到NSUserDefaults,如下所示。

第一个区块代码:

    - (void)receivedLoginData:(NSData *)data
{
    //NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    // NSLog(@"%@",newStr);
    NSError *localError = nil;
    self.parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];
    NSString* loginResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];


    NSData *jsonData = [loginResponse dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    NSString *statusCode = [NSString stringWithFormat:@"%@",jsonDic[@"status"]];

    self.statusCode = [NSString stringWithFormat:@"%@",jsonDic[@"status"]];
//     NSLog(@"Setting is %@", self.statusCode);
//     NSLog(@"%@",loginResponse );
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

    [prefs setObject:statusCode forKey:@"statusCode"];
    [prefs synchronize];

}

LoginController有以下代码。在这里我试图通过调用[self.request loginValidation];

从NSUserDefaults检索状态代码
if (([self.request.usernameText isEqualToString:@""] && [self.request.passwordText isEqualToString:@""]) || ([self.request.usernameText isEqualToString:self.usernameTextField.text] && [self.request.passwordText isEqualToString:@""]) || ([self.request.usernameText isEqualToString:@""] && [self.request.passwordText isEqualToString:self.passwordTextField.text]))

        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"Username or Password cant be left empty." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [self performSelector:@selector(select) withObject:self.request afterDelay:.1];
        } else{
            [self.request loginValidation];
            NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
            NSString* strValue =    [defaults objectForKey:@"statusCode"];
            NSLog(@"code %@",strValue);

        }

第一次运行应用程序并提供正确的登录凭据时,在APIRequest.m文件中设置的状态代码为1,因此当检索到该值时,该值仍为1.

第二次我尝试提供错误的登录凭据,因此在APIRequest.m文件中设置的状态代码为0但是当它被检索时,该值仍为1.我如何解决此冲突?

1 个答案:

答案 0 :(得分:2)

好的,这是主要问题,[self.request loginValidation];将在后台线程中调用代码,并等到响应到来,底线将被执行,而不等待登录验证实际完成。

更好的方法是在收到数据后调用函数检查登录 - >

self.statusCode = [NSString stringWithFormat:@"%@",jsonDic[@"status"]];
//     NSLog(@"Setting is %@", self.statusCode);
//     NSLog(@"%@",loginResponse );
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

[prefs setObject:statusCode forKey:@"statusCode"];
[prefs synchronize];
[self confirmValidation];


-(void) confirmValidation
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSString* strValue =    [defaults objectForKey:@"statusCode"];
    NSLog(@"code %@",strValue);

}

现在,如果他们不在同一个班级或无法直接沟通,请使用通知中心。

它很简单,在你调用[self.request loginValidation];的控制器中,在viewDidLoad或某个地方添加一个观察者 - >

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(didSuccessfullyLogin:)
                                             name:@"didSuccessfullyLogin"
                                           object:nil];

一个功能 - >

- (void) didSuccessfullyLogin:(NSNotification *) notification
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSString* strValue =    [defaults objectForKey:@"statusCode"];
    NSLog(@"code %@",strValue);
}

最后,

self.statusCode = [NSString stringWithFormat:@"%@",jsonDic[@"status"]];
//     NSLog(@"Setting is %@", self.statusCode);
//     NSLog(@"%@",loginResponse );
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

[prefs setObject:statusCode forKey:@"statusCode"];
[prefs synchronize];
[[NSNotificationCenter defaultCenter]
 postNotificationName:@"didSuccessfullyLogin"
 object:self];

希望这有帮助。