如何从 objective c 中的块中 return 布尔值?
How to return boolean from a block in objective c?
大家好,在用户选择允许或不允许访问照片库的选项后,尝试对我从块中调用的方法 return 一个布尔值。我怎样才能 return 来自这个特定块的布尔值?
(BOOL)checkIfUserHasAccessToPhotosLibrary{
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusNotDetermined) {
NSLog(@"Access has not been determined check again");
__block BOOL boolean=false;
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {
NSLog(@"User responded has access to photos library");
boolean=true;
}
else {
NSLog(@"User responded does has access to photos library");
boolean=false;
}
}];
}
}
您问的是:
How to return boolean from a block in objective c?
你没有。
您在方法中使用了完成处理程序块参数,可能像这样:
- (void)checkPhotosLibraryAccessWithCompletion:(void (^ _Nonnull)(BOOL))completion {
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusNotDetermined) {
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
completion(status == PHAuthorizationStatusAuthorized);
}];
} else {
completion(status == PHAuthorizationStatusAuthorized);
}
}
然后你会像这样使用它:
[self checkPhotosLibraryAccessWithCompletion:^(BOOL success) {
// use success here
if (success) {
...
} else {
...
}
}];
// but not here, because the above runs asynchronously (i.e. later)
大家好,在用户选择允许或不允许访问照片库的选项后,尝试对我从块中调用的方法 return 一个布尔值。我怎样才能 return 来自这个特定块的布尔值?
(BOOL)checkIfUserHasAccessToPhotosLibrary{
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusNotDetermined) {
NSLog(@"Access has not been determined check again");
__block BOOL boolean=false;
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {
NSLog(@"User responded has access to photos library");
boolean=true;
}
else {
NSLog(@"User responded does has access to photos library");
boolean=false;
}
}];
}
}
您问的是:
How to return boolean from a block in objective c?
你没有。
您在方法中使用了完成处理程序块参数,可能像这样:
- (void)checkPhotosLibraryAccessWithCompletion:(void (^ _Nonnull)(BOOL))completion {
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusNotDetermined) {
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
completion(status == PHAuthorizationStatusAuthorized);
}];
} else {
completion(status == PHAuthorizationStatusAuthorized);
}
}
然后你会像这样使用它:
[self checkPhotosLibraryAccessWithCompletion:^(BOOL success) {
// use success here
if (success) {
...
} else {
...
}
}];
// but not here, because the above runs asynchronously (i.e. later)