分配给&#39; id <uinavigationcontrollerdelegate,uiimagepickercontrollerdelegate>&#39;来自不兼容的类型&#39; ViewController * const__strong&#39; </uinavigationcontrollerdelegate,uiimagepickercontrollerdelegate>

时间:2014-10-17 13:58:52

标签: ios xcode delegates uiimagepickercontroller incompatibletypeerror

我的应用程序中有一个ImagePickerController。 它运行良好,但在ipc.delegate = self;旁边出现错误消息:

  

分配给   &#39; ID&#39;   来自不兼容的类型&#39; ViewController * const__strong&#39;

该应用程序运行良好,所以我忽略了错误消息,但我想我需要知道原因。为什么会出现错误消息?

ipc = [[UIImagePickerController alloc]init];
            ipc.modalPresentationStyle = UIModalPresentationCurrentContext;
            ipc.delegate = self;
            ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [ipc setAllowsEditing:NO];
            [self presentViewController:ipc animated:NO completion:nil];

2 个答案:

答案 0 :(得分:16)

如果您查看UIImagePickerController委托属性的定义,您会将其定义为:

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

您设置为委托的任何对象(在这种情况下,您使用self)必须符合UINavigationControllerDelegate协议和UIImagePickerControllerDelegate协议。如果对象不符合这两个协议,您将收到编译时警告。

以下是您如何声明您的班级符合协议的方式:

@interface MyViewController : UIViewController <UINavigationControllerDelegate, 
                                                UIImagePickerControllerDelegate>

阅读working with protocolsUINavigationControllerDelegateUIImagePickerControllerDelegate

答案 1 :(得分:5)

我刚刚第一次遇到这个问题。如果您的类扩展了另一个符合其他协议的类,并且您的类也符合这两个协议<UINavigationControllerDelegate, UIImagePickerControllerDelegate>,那么为了删除警告,您必须强制转换它,如下所示:

ipc.delegate = (id<<UINavigationControllerDelegate, UIImagePickerControllerDelegate>) self;

就个人而言,我认为这是编译器中的一个错误,因为你确实遵守这两个协议,你也恰好坚持其他协议。因此,您不必看警告。