【问题标题】:Subclassing UIPageViewController, but when I assign the result of [[alloc] init] to self, I get a warning. Why?子类化 UIPageViewController,但是当我将 [[alloc] init] 的结果分配给 self 时,我收到警告。为什么?
【发布时间】:2014-02-16 18:34:35
【问题描述】:
我有一个名为ImageGalleryPageViewController 的类,它是UIPageViewController 的子类。我在它的 init 方法中调用:
self = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
但我收到此警告:
从 'UIPageViewController *' 分配给 'ImageGalleryPageViewController *' 的指针类型不兼容
我应该只转换[[alloc] init] 的结果吗?这看起来很奇怪,它不应该承认我是一个子类而不是抱怨吗?
【问题讨论】:
标签:
ios
objective-c
cocoa-touch
uiviewcontroller
uipageviewcontroller
【解决方案1】:
你应该使用
self = [super initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
当有人在您的子类上调用alloc] init* 时,他们正在使用alloc 创建一个实例,然后init* 方法初始化该对象。你正在做的是创建一个全新的对象alloc] init*,这意味着之前分配的对象将被立即丢弃。
请记住,如果您将子类的实例分配给它的父类的指针,编译器会很高兴,因为编译器知道子类将具有相同的接口
@interface SubClass : SuperClass
SuperClass *instance = [[SubClass alloc] init]; // This is fine
但它不能保证反过来,例如父类将实现子类将添加的其他行为
@interface SubClass : SuperClass
SubClass *instance = [[SuperClass alloc] init]; // warning
【解决方案2】:
您基本上是在丢弃当前实例(ImageGalleryPageViewController 的实例并将其替换为 UIPageViewController 的新实例,这就是您收到警告的原因。
您应该在这里调用super,而不是创建新实例,并将self 分配给结果:
self = [super initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];