当变量已经定义了类型时,为什么需要类型转换?

Why is type cast necessary when variable is already defining the type?

我有一个自定义的 UIViewController,用作弹出窗口的内容视图控制器。这个自定义的 UIViewController 是这样定义的...

@interface MyCustomViewController : UIViewController <MyCustomDelegate>

然后我在另一个 class 中有一个方法,我在其中引用弹出窗口的 contentViewController,就像这样...

-(void)someMethod:(UIPopoverController *)popoverController

    UIViewController<MuCustomDelegate> *theCustomViewController;

所以既然我已经定义了 theCustomViewController 是什么,为什么我必须在那之后的下一行做这个...

theCustomViewController = (UIViewController<MyCustomDelegate>*)myUIPopOverController.contentViewController;

为什么编译器/XCode 编辑器或其他任何东西都不知道委托是什么,而不是让我在定义它之后强制转换它

谢谢

常见的模式是:

// in MyClass.h
@protocol MyClassDelegate;

@interface MyClass : NSObject
@property(weak,nonatomic) id<MyClassDelegate>delegate;
@end

@protocol MyClassDelegate <NSObject>
- (NSInteger)myClassNeedsAnInt:(MyClass *)instanceOfMyClass;
@end

完成后,在 MyClass.m 中应该很容易说,无需进一步转换:

NSInteger anInt = [self.delegate myClassNeedsAnInt:self];

此 class 的一位客户说:

// in MyCustomerClass.h or in a private interface in .m
#import "MyClass.h"

@interface MyCustomerClass : NSObject <MyClassDelegate>
@end

并在其实现中,将自己设置为委托并实现委托协议:

MyClass *myClassInstance = [[MyClass alloc] init];
myClassInstance.delegate = self;

- (NSInteger)myClassNeedsAnInt:(MyClass *)instanceOfMyClass {
    return 42;
}

根据您的更新,您询问是否需要投射 myUIPopOverController.contentViewController

简单 - contentViewController 属性 的类型为 UIViewController *。您不能将其直接分配给 UIViewController<MuCustomDelegate> *.

类型的变量

协议的添加意味着您需要特定类型的 UIViewController。编译器不能假设 contentViewController 恰好是这样一个值。所以你使用强制转换告诉编译器,"trust me, I know what it really is".