从不兼容的类型分配给可空的 ID

Assigning to ID Nullable from Incompatible Types

我在 XCode 中出现了这个警告,我似乎无法摆脱它。

Assigning to 'id < UINavigationControllerDelegate, UIImagePickerControllerDelegate > _Nullable ' from incompatibale type 'MyViewController * const _strong'

这一行:

picker.delegate = self;

这行代码使应用程序按预期工作。 所以删除它,它不起作用。但我不知道如何摆脱错误。有帮助吗?

其他分配了委托的方法不会抛出此警告。

视图控制器是嵌入在 NavigationController 中的 TabBarViewController 的一部分。

我的 class 继承了 UIImagePickerControllerDelegate

@interface MyViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate, UIActionSheetDelegate, UICollectionViewDelegateFlowLayout> {

}
///...
@end

以及完整的方法。

- (void) showImagePickerForSourceType:(UIImagePickerControllerSourceType)sourceType {

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.modalPresentationStyle = UIModalPresentationCurrentContext;
    picker.sourceType = sourceType;
    picker.delegate = self; ///HERE IS THE ISSUE
    picker.modalPresentationStyle = UIModalPresentationFullScreen;
    picker.modalTransitionStyle   = UIModalTransitionStyleCoverVertical;

    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        picker.showsCameraControls = YES;
    }

    [self presentViewController:picker animated:YES completion:nil];
}

添加 UINavigationControllerDelegateUIImagePickerControllerDelegate 会为我隐藏该警告。

在 UIKit 中,图像选择器的委托指定为:

@property(nullable,nonatomic,weak) id <UINavigationControllerDelegate, UIImagePickerControllerDelegate> delegate;

来自文档:

图像选择器的委托对象。

声明

SWIFT

weak var delegate: protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>?

OBJECTIVE-C

@property(nonatomic, weak) id<UINavigationControllerDelegate, UIImagePickerControllerDelegate> delegate

讨论

当用户选择图像或电影,或退出选择器界面时,代理会收到通知。委托还决定何时关闭选择器界面,因此您必须提供委托才能使用选择器。如果此 属性 为 nil,如果您尝试显示它,选择器会立即被关闭。

除了 UIImagePickerControllerDelegate 之外,您还需要 UINavigationControllerDelegate

@interface MyViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate, UICollectionViewDelegateFlowLayout> {

}