加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ios – 获取警告设置自定义协议的委托

发布时间:2020-12-14 17:17:08 所属栏目:百科 来源:网络整理
导读:我在我的一个类中添加了一个自定义协议,当我尝试在prepareForSegue:方法期间设置委托时,我收到编译器警告.我得到的警告是…… Sending 'MyCustomViewControllerClass *const __strong' to parameter of incompatible type 'idNSFileManagerDelegate' 项目构
我在我的一个类中添加了一个自定义协议,当我尝试在prepareForSegue:方法期间设置委托时,我收到编译器警告.我得到的警告是……

Sending 'MyCustomViewControllerClass *const __strong' to parameter of incompatible type 'id<NSFileManagerDelegate>'

项目构建和运行,一切正常,减去警告.如果我添加< NSFileManagerDelegate>我的自定义类警告消失了.我错过了什么,或者这是Xcode(6 beta)中的错误?代码是设置协议/委托的标准代码,但无论如何我都会发布它…

SomeSecondClass.h

#import <UIKit/UIKit>

@class SomeSecondCustomViewController;

@protocol SomeSecondCustomViewControllerDelegate <NSObject>
- (void)doThisForMe
@end

@interface SomeSecondCustomViewController : UIViewController

@property (weak,nonatomic) id <SomeSecondCustomViewControllerDelegate> delegate;

@end

SomeSecondClass.m

@interface SomeSecondViewController ()
…stuff

-(void)someMethod {

    [self.delegate doThisForMe];
}

@end

CustomClass.h

#import <UIKit/UIKit.h>
#import “ SomeSecondViewController.h”

@interface MyCustomViewController : UIViewController <SomeSecondCustomViewControllerDelegate>
//adding on <NSFileManagerDelegate> removes the warning...
@end

CustomClass.h

...standard stuff...

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"MySegue"]) {

         //this is where the warning happens on "self"
         [segue.destinationViewController setDelegate:self];

    }
}


- (void)doThisForMe {

   //doing some stuff...

}
@end

我已经打开了之前没有警告的项目,现在出现了相同的警告.我想知道这是否是一个Xcode问题?

解决方法

您遇到的问题是Objective-C如何找到匹配的选择器并处理id引用时出现歧义.

UIStoryboardSegue destinationViewController返回一个id.然后,您的代码尝试在此id引用上调用setDelegate方法.由于没有关于此id实际引用的信息,因此它不知道您可能指的是哪个setDelegate:方法(有很多).因此,编译器扫描它知道的列表并选择一个.在这种情况下,它从NSFileManager类中选择了setDelegate:方法.由于self不符合NSFileManagerDelegate协议,因此会收到警告.

您可以忽略该警告,在这种情况下您的代码将正常工作.

更好的解决方案是通过添加强制转换来帮助编译器:

[(SomeSecondCustomViewController *)segue.destinationViewController setDelegate:self];

这将让编译器知道你真正想要的setDelegate:方法.

顺便说一句 – 将NSFileManagerDelegate添加到您的类中并不是一个有效的解决方案,即使它现在正常工作.对某些import语句进行简单的重新排序可能会导致编译器做出不同的选择,并且您的警告会返回,但会抱怨不符合其他协议.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读