我有以下方法来检查我的数据库中是否已存在电子邮件:
-(BOOL) emailHasBeenTaken:(NSString *)email
{
PFQuery *query = [PFUser query];
[query whereKey:@"email" equalTo:email];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error && objects.count>0) {
NSLog(@"in the emailHasbeenTaken EMAIL IS DUPLICATE");
[self duplicateEmail];
} else
{
NSLog(@"in the emailHasBeenTaken, EMAIL IS NOT EXISTENT");
}
}];
return YES;
}
我遇到的问题是,有时它会起作用,有时它会不会,我不确定我做错了什么,我的意思是工作与否是这个...我检查新用户是否正在尝试使用以下代码注册:
if (![self emailHasBeenTaken:self.emailTF.text]) {
// EMAIL WAS NOT FOUND IN DATABASE SO IT WILL ASSIGN THE
TEXTFIELD VALUES TO USER PROPERTIES
email = self.emailTF.text;
user.email = email;
} else
{
[self duplicateEmail];
return;
}
我做错了什么?为什么我发现自己将!
添加到我的if语句中以获得所需的结果..有没有办法从BOOL
语句接收多个返回?即一个案例将返回YES而另一个案件将返回NO。
答案 0 :(得分:4)
首先,你正在对Parse进行异步调用,它什么都不做(除了调用你没有发布的duplicateEmail
方法,所以我不知道那是什么)然后你总是返回来自YES
方法的emailHasBeenTaken:
。
由于您需要进行异步调用以获取具有该电子邮件的任何用户,因此您需要重新格式化方法的工作方式。您需要将其更改为以下内容:
- (void)emailHasBeenTaken:(NSString *)email completion:(void(^)(BOOL emailIsTaken, NSError *error))completionBlock
{
void (^completionCopy)(BOOL, NSError *) = [completionBlock copy];
PFQuery *query = [PFUser query];
[query whereKey:@"email" equalTo:email];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(@"in the emailHasbeenTaken ERROR HAS OCCURRED");
if (completionCopy) {
completionCopy(NO, error);
}
return;
}
if (objects.count > 0) {
NSLog(@"in the emailHasbeenTaken EMAIL IS DUPLICATE");
if (completionCopy) {
completionCopy(YES, nil);
}
}
else {
NSLog(@"in the emailHasBeenTaken, EMAIL IS NOT EXISTENT");
if (completionCopy) {
completionCopy(NO, nil);
}
}
}];
}
请注意,此方法现在本身是异步的,因此无法将其用作if
语句中的条件。你会改为使用它:
NSString *emailFromTextField = self.emailTF.text;
[self emailHasBeenTaken:emailFromTextField completion:^(BOOL emailIsTaken, NSError *error) {
if (error) {
// TODO: handle any errors here
return;
}
if (!emailIsTaken) {
// Assuming "email" and "user" are instance variables here:
email = emailFromTextField;
user.email = email;
}
else {
[self duplicateEmail];
}
}];
答案 1 :(得分:3)
您总是返回YES
。