gpt4 book ai didi

ios - 子类化 UIPageViewController,但是当我将 [[alloc] init] 的结果分配给自己时,我收到警告。为什么?

转载 作者:行者123 更新时间:2023-11-28 18:20:21 25 4
gpt4 key购买 nike

我有一个名为 ImageGalleryPageViewController 的类,它是 UIPageViewController 的子类。在它的 init 方法中,我调用:

self = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];

但是我收到这个警告:

Incompatible pointer types assigning to 'ImageGalleryPageViewController *' from 'UIPageViewController *'

我应该只转换 [[alloc] init] 的结果吗?这看起来很奇怪,难道它不应该承认我是一个子类而不提示吗?

最佳答案

你应该使用

self = [super initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];

当有人在您的子类上调用 alloc] init* 时,他们正在使用 alloc 创建实例,然后 init* 方法初始化对象.您正在做的是创建一个全新的对象 alloc] init*,这意味着之前分配的对象将立即被丢弃。

请记住,如果您将子类的实例分配给它的父类的指针,编译器会很高兴,因为编译器知道子类将具有相同的接口(interface)

@interface SubClass : SuperClass

SuperClass *instance = [[SubClass alloc] init]; // This is fine

但它不能保证反过来 e.g.父类将实现子类将添加的额外行为

@interface SubClass : SuperClass

SubClass *instance = [[SuperClass alloc] init]; // warning

关于ios - 子类化 UIPageViewController,但是当我将 [[alloc] init] 的结果分配给自己时,我收到警告。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21815616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com