Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

General Discussion

Logging In and Logging Out Code Challenge

In the code challenge for logging in and logging out, I keep getting this wrong and I don't know if I'm being stupid but I really can't figure it out...

It's part 2 of 4 with this question: In viewDidLoad we see that the LoginViewController is presented automatically. Set the 'currentUser' variable using the appropriate method from the PFUser class. Then use that variable in an if statement to only perform the segue to LoginViewController if no user is logged in.

Here's my code:

#import "MainViewController.h"
#import "LoginViewController.h"
#import <Parse/Parse.h>

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    PFUser *currentUser = [PFUser currentUser];
    if (currentUser == nil) {
        [self performSegueWithIdentifier:@"showLogin" sender:self];
    }

    [self performSegueWithIdentifier:@"showLogin" sender:self];
}

- (IBAction)logOut:(id)sender {

    [self performSegueWithIdentifier:@"showLogin" sender:self];
}

@end

You are calling the method :

[self performSegueWithIdentifier:@"showLogin" sender:self]

two times. Once inside the scope of :

if (currentUser == nil) {
    }

which is correct. The second time is in the scope of:

- (void)viewDidLoad {
}

which would be causing your conflict.

I much prefer using the statement below because it also sets up a a way for us to act on if the currentUser exists:

- (void)viewDidLoad {
    [super viewDidLoad];

    PFUser *currentUser;
    currentUser = [PFUser currentUser];
    if (currentUser) {
    }
else {
    [self performSegueWithIdentifier:@"showLogin" sender:self];
    }
}

1 Answer

#import "MainViewController.h"
#import "LoginViewController.h"
#import <Parse/Parse.h>

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];


PFUser *currentUser = [PFUser currentUser];
if (currentUser) {
    // do stuff with the user
} else {
    // show the signup or login screen
}
}



- (IBAction)logOut:(id)sender {

    [self performSegueWithIdentifier:@"showLogin" sender:self];
}

@end