【问题标题】:Use of undeclared identifier alloc?使用未声明的标识符 alloc?
【发布时间】:2026-01-01 01:05:02
【问题描述】:

当我尝试使用此代码创建自定义类的实例时...

PlayerTurn *playerTurn = [[alloc] init];

...在我的视图控制器.m 文件中的方法定义中,我收到此错误:

“使用未声明的标识符 alloc”

谁能解释一下!?我认为 alloc-init 很简单。

【问题讨论】:

  • alloc 是一种方法。它需要被调用。

标签: objective-c alloc undeclared-identifier


【解决方案1】:

alloc 是一个类方法(实际上适用于所有类)。您需要在要为其创建实例的类上调用它。所以你想要:

PlayerTurn *playerTurn = [[PlayerTurn alloc] init];
//                         ^^^^^^^^^^

【讨论】:

    【解决方案2】:

    我想你的意思是:

    PlayerTurn *playerTurn = [[PlayerTurn alloc] init];
    

    来自 Apple 的 Working with Objects 文档可能会有所帮助。

    【讨论】:

    • 我想我现在就去开枪。对于最愚蠢的问题,您应该在此网站上获得奖励
    • @Dave 太糟糕了,没有手掌表情符号(尽管明年可能会有)。