ios - 从指定的初始化程序调用超静态方法

标签 ios objective-c sprite-kit

[SKNode 节点] 返回一个初始化节点。 ( https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKNode_Ref/Reference/Reference.html#//apple_ref/occ/clm/SKNode/node )

如果我子类化 SKNode:

@interface MyClass : SKNode

然后在 MyClass 内的指定初始化程序中调用 super 指定初始化程序(类方法)。

@implementation MyClass
{ 
    MyScene _MyScene;
}

- (instancetype)initWithScene:(MyScene *)myScene
{
    _MyScene = myScene;
    if (self = [SKNode node]) { // HERE I GET ERROR
     }
     return self;

}

错误:将赋值结果用作不带括号的条件 如果我将其更改为:

if ((self = [SKNode node]))

我得到:从 (SKNode *) 分配给 (MyClass *) 的不兼容指针类型 如果它是类方法,调用 super 指定初始化程序的方法是什么?我也试过 调用 self = (MyClass *)[SKNode node] 但我得到一个奇怪的错误。

最佳答案

I get: incompatible pointer types assigning to (MyClass *) from (SKNode *)

问题是 [SKNode node]SKNode 的实例中分配和初始化,这意味着您没有机会将该对象转换为实例你自己的子类。你得到不兼容的指针错误,因为你试图将 SKNode * 分配给 self,它是 MyClass * 类型。

相反,您需要自己进行分配,以便在父类(super class)完成初始化后为您的实例变量留下足够的空间。所以,做类似的事情:

self = [super init];
if (self) {
//...
}

I also tried calling self = (MyClass *)[SKNode node] but i get an strange error.

这基本上是同一个问题。将 [SKNode node] 转换为类型 MyClass * 不会改变对象本身是 SKNode 实例的事实,而不是我的类。同样,您需要创建一个 MyClass 实例(使用 +alloc),然后调用父类(super class)的 (SKNode) 初始化器,并且 然后 执行MyClass 初始化。

关于ios - 从指定的初始化程序调用超静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22914796/

相关文章:

swift - SpriteKit : Sprites are moving through each other with a physicsBody already set

ios - 错误 : Invalid Swift Support when uploading a build to iTunes Connect

ios - 在 iOS 的 C 函数中使用 ARC 取消引用指针

ios - 在 Swift 3 中获取 Google Drive iOS 基本目录中的文件夹列表?

ios - 我应该寻找什么 API 来在屏幕底部的 UIView 中显示 UIButtons 或 UITableViewCells?

ios - MPMediaQuery 仅返回本地项目

swift - 为什么 applyImpulse 在 swift spritekit 中不起作用?

ios - SpriteKit : changing zRotation in DidBeginContact

ios - Objective-c 中的空格

ios - Facebook 应用程序评论 iOS - 无法选择 "Download it from the Apple App Store"