如何在Objective C块中更改BOOL局部变量的值?我用过" __ block"符号,但它不起作用
- (BOOL)loginUserWithEmail:(NSString *)email andPassword:(NSString *)password {
__block BOOL result = NO;
SCPredicate *emailPredicate = [SCPredicate whereKey:@"email" isEqualToString:email];
SCPredicate *passwordPredicate = [SCPredicate whereKey:@"password" isEqualToString:password];
SCCompoundPredicate *compoundPredicate = [SCCompoundPredicate compoundPredicateWithPredicates:@[emailPredicate, passwordPredicate]];
[[SHPerson please] giveMeDataObjectsWithPredicate:compoundPredicate parameters:nil completion:^(NSArray *persons, NSError *error) {
if (persons != nil) {
result = YES;
}
}];
return result;
}
答案 0 :(得分:1)
您的问题是该方法在您的异步giveMeDataObjectsWithPredicate
方法有时间完成之前返回NO的结果。试试这个:
- (void)loginUserWithEmail:(NSString *)email andPassword:(NSString *)password withCompletion:(void(^)(BOOL result))completion {
SCPredicate *emailPredicate = [SCPredicate whereKey:@"email" isEqualToString:email];
SCPredicate *passwordPredicate = [SCPredicate whereKey:@"password" isEqualToString:password];
SCCompoundPredicate *compoundPredicate = [SCCompoundPredicate compoundPredicateWithPredicates:@[emailPredicate, passwordPredicate]];
[[SHPerson please] giveMeDataObjectsWithPredicate:compoundPredicate parameters:nil completion:^(NSArray *persons, NSError *error) {
if (completion) {
if (persons != nil) {
completion(YES);
} else {
completion(NO);
}
}
}];
}
然后您可以将其用于:
[self loginUserWithEmail:email andPassword:password andCompletion:^(BOOL result) {
// You can now use result here...
}];