Objective C 实例变量尽管被保留但仍被释放
我有一个棉花糖类,它(除其他外)有一个 CCSprite 对象作为实例变量。
这是 init 方法:
-(id) init
{
if((self = [super init]))
{
model = [[CCSprite spriteWithFile:@"marshmallow.png"] retain];
maxSpeed = 5; //160px per second (maxspeed * PTM_Ratio = px/second max)
gravity = 9.81; // in meters/sec^2
health = 3;
}
return self;
}
该变量在另一个文件中声明为全局变量,并使用以下行:
Marshmallow *mainChar;
稍后在文件中,使用此行设置(初始化/分配):
mainChar = [[mainChar alloc] init];
在编写上一行时,xcode 给了我一个警告 Marshmallow 可能不会响应分配。 (我不认为这是相关的。只是提到任何看起来错误的东西)
我的问题是以下代码行返回 nil:
[mainChar getModel];
为什么它返回 nil 而不是实例变量?
这是 getModel 函数:
-(CCSprite *)getModel
{
return model;
}
I have a marshmallow class which has (among other things) a CCSprite object as an instance variable.
here is the init method:
-(id) init
{
if((self = [super init]))
{
model = [[CCSprite spriteWithFile:@"marshmallow.png"] retain];
maxSpeed = 5; //160px per second (maxspeed * PTM_Ratio = px/second max)
gravity = 9.81; // in meters/sec^2
health = 3;
}
return self;
}
the variable is declared in another file as a global variable with the line:
Marshmallow *mainChar;
Later in the file, it is set (initiated/alloc'd) with this line:
mainChar = [[mainChar alloc] init];
while writing the previous line, xcode gave me a warning that Marshmallow might not respond to alloc. (I don't think that's related. just mentioning anything that seems wrong)
my problem is that the following line of code returns nil:
[mainChar getModel];
why does it return nil instead of the instance variable?
here is the getModel function:
-(CCSprite *)getModel
{
return model;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不应该吗
?
该消息表示该类的对象可能不会响应它,而不是类本身。
Shouldn't be
?
The message says an object from that class might not respond to it, not the class itself.
您的问题在于
mainChar
变量的初始化。您要查找的行是这样的:您收到的警告告诉您
Marshmallow
类型的实例将不会响应-alloc
消息。这就是你的问题:你想调用+alloc
类方法,如下所示:Your problem is in the initialization of your
mainChar
variable. The line you're looking for is this:The warning you got is telling you that instances of type
Marshmallow
will not respond to the-alloc
message. That is your problem: you want to call the+alloc
class method instead, like so:我认为你想做的
不是
你得到的错误消息非常重要。
I think you want to do
instead of
The error message you got is very important.