【发布时间】:2010-12-03 01:19:22
【问题描述】:
在 cocos2d-iphone 中我有一个名为 GameScene 的 CCLayer 类
我想从另一个类中使用这个类,但是我不知道 GameScene 类的实例的名称
我如下初始化了一个GameScene类的实例
-(id) init {
if ((self = [super init])) {
但是这不会给我实例的名称
我在文档中读到可以使用名为 initWithName 的方法,因此我尝试了类似的方法,但它不起作用,它给了我警告:
In function '-[GameScene init]':
warning: 'CCLayer' may not respond to '-initWithName:'
我试过的代码是
-(id) init {
if ((self = [super initWithName:"gamescene"])) {
我在游戏中只需要这个类的一个实例,但我无法捕获该实例的处理程序,以便我可以从其他类中使用它?
任何想法
非常感谢
更新:
你好
我将更新代码,让您知道我已经尝试过您的解决方案,但它似乎还没有工作
在 MyAppDelegate.h 我有这行代码:
首先我定义了应用程序委托以与其他类共享它
MyAppDelegate.h
#define AD (MyAppDelegate *)[[UIApplication sharedApplication] delegate]
在 MyAppDelegate.m 我有以下代码:
gs = [[GameScene alloc] init];//this is the gamescene
sc = [gs scene]; //this calls the method -(id)(scene)
[[CCDirector sharedDirector] runWithScene: sc]; //runwithscene
现在当我尝试在其他类中使用 gs 时——例如 player.m 类——
播放器.m
GameScene* gs = [AD gs]; //retrieving the instance from appdelegate
[gs updateScoreByAmount:5];/calling the method "updateScoreByAmount"
结果,猜猜会发生什么?
程序运行没有错误,但 gs 实例似乎与 appdelegate 运行的不同,因为此方法“updateScoreByAmount”不会影响 appdelegate 中的 runWithScene 运行的场景
有什么想法吗?
非常感谢所有尝试提供帮助的人
【问题讨论】:
-
这是一个非常令人困惑的问题。对象本身没有名称。很难确定您正在尝试做什么以及您在做这件事时遇到了什么样的麻烦。
-
试试
if ((self = [super initWithName:@"gamescene"])) -
@Ryan,我只是想从另一个类访问游戏场景类的方法?
-
@vikingosegundo:不幸的是,这不起作用,谢谢
-
如果您在创建对象后对如何引用它感到困惑,您应该参考下面 darren 的回答。 Objective-C 与所有其他基于 C 的语言一样工作,因为对象不是通过实例化时给出的固有名称访问的,而是通过对对象的变量引用,如 darren 的示例。
标签: objective-c cocoa oop cocos2d-iphone