Cocoa-Touch - 代表混淆

Pet*_*rbo 27 cocoa-touch delegates objective-c uiapplicationdelegate automatic-ref-counting

我刚刚开始运行Xcode 4.2.1和iOS5 SDK的新项目.该项目是使用ARC设置的.我正在尝试将AppDelegate设置为UITabBarController的委托,[tabBarController setDelegate:self];如果我这样做,我会收到一条警告消息:

warning: Semantic Issue: Sending 'AppDelegate *const __strong' to parameter of incompatible type 'id<UITabBarControllerDelegate>'
Run Code Online (Sandbox Code Playgroud)

好吧,我设置我的AppDelegate以符合UITabBarControllerDelegate

@interface AppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate>
Run Code Online (Sandbox Code Playgroud)

好的,警告消失了.

我现在得到另一个错误.在一个视图控制器中,我希望得到一个AppDelegate,所以我这样做:AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];但这会发出警告说:

warning: Semantic Issue: Initializing 'AppDelegate *__strong' with an expression of incompatible type 'id<UIApplicationDelegate>'
Run Code Online (Sandbox Code Playgroud)

但如果我删除我的AppDelegate符合UITabControllerDelegate协议我的第二个警告消失.

非常奇怪的行为,是什么让Cocoa专家?

Ila*_*ian 82

在分配AppDelegate变量之前尝试进行类型转换.

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
Run Code Online (Sandbox Code Playgroud)

而且,保持UITabControllerDelegate.

  • 嗨@Aadhira,这解决了我的错误,但我不确定我理解为什么解决方案有效.你或者有人会介意向我解释吗?谢谢! (2认同)