質問

I have a class called ImageGalleryPageViewController that is a subclass of UIPageViewController. In its init method I call:

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

But I get this warning:

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

Should I just cast the result of the [[alloc] init]? That seems odd, shouldn't it recognize that I'm a subclass and not complain?

役に立ちましたか?

解決

You should use

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

When someone calls alloc] init* on your subclass they are creating an instance with alloc and then the init* method initialises the object. What you were doing is creating an entirely new object alloc] init* which would mean that the previously allocated object would be thrown away immediately.

Keep in mind that that the compiler will be happy if you assign an instance of subclass to a pointer of it's parent class as the compiler knows that the subclass will have the same interface

@interface SubClass : SuperClass

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

but it can not guarantee the other way round e.g. that a parent class will implement additional behaviour that a subclass will add

@interface SubClass : SuperClass

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

他のヒント

You're basically throwing away your current instance (the instance of your ImageGalleryPageViewController and replacing it with a new instance of UIPageViewController, which is why you get the warning.

You should call super here, not create a new instance, and assign self to the result of that:

self = [super initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top