问题
I can't figure out how to retrieve a boolean from the user class in Parse. This code doesn't work for me:
PFUser *user = [PFUser currentUser];
NSNumber *boolNumber = [user objectForKey:@"bool"];
BOOL b = [boolNumber boolValue];
NSLog(@"%d", b);
Anyone know the proper way to do this?
回答1:
Everything you're doing looks fine on retrieval. It's probably an error with the way you are setting the variable/saving the user. Try something like this and see if it works.
PFUser *user = [PFUser currentUser];
user[@"likesFruit"] = @(YES); // You can set it to @(NO) also. It doesn't matter. This is just an example.
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (succeeded) {
BOOL likesFruit = [user[@"likesFruit"] boolValue];
NSLog(@"Does this user like fruit?\n%@", (likesFruit) ? @"Yes" : @"No");
} else {
NSLog(@"Error saving user: %@", error);
}
}];
Another way to make sure your retrieval is safe is this:
[user fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!error) {
BOOL likesFruit = [object[@"likesFruit"] boolValue];
NSLog(@"This user %@ like fruit", likesFruit ? @"does" : @"doesn't");
} else {
NSLog(@"Error retrieving user data: %@", error);
}
}];
回答2:
Try this:
PFUser *user = [PFUser currentUser];
BOOL boolean = [[user objectForKey@"bool"] boolValue];
来源:https://stackoverflow.com/questions/25190147/retrieve-boolean-from-user-class-in-parse