Retrieve boolean from user class in Parse

自作多情 提交于 2020-01-24 23:04:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!