从NSArray检索类对象并添加到self [英] Retrieving Class Object from NSArray and adding to self
问题描述
您尝试从NSMutableArray检索特定类的对象,然后将其添加到self:例如:
Hi im trying to retrieve an object of a specific class from an NSMutableArray, and then add it to self: eg:
- (void) init{
_Objects = [[NSMutableArray alloc]init];
Psychicing *psy = [[Psychicing alloc]init];
[psy startPsychic];
[_Objects addObject: psy];
[psy release];
}
这将创建一个Psychicing类的对象,然后运行[psy startPsychic]方法创建类对象的内部。然后我添加psy对象到_Objects NSMutableArray。
This creates an object of class Psychicing, then runs the [psy startPsychic] method to create the internals of the class object. Then I add the psy object to _Objects NSMutableArray.
-(void)startPsychic{
id psychicParticle = [CCParticleSystemQuad ......]; //is Synthesised with (assign)
//Other things are set here such as position, gravity, speed etc...
}
当在屏幕上检测到触摸时,我想从_Objects数组中获取psy对象并将其添加到self:这样的东西(虽然这会导致运行时错误) / p>
When a touch is detected on screen, I want to take the psy object from the _Objects array and add it to self: Something like this (Although this gives runtime error)
-(void) Touches.....{
for (Psychicing *psy in _Objects){
[self addChild: psy.psychicParticle];
}
}
我希望我已经解释得很清楚,如果你需要更多的澄清让我知道。
所以基本上:
[MainClass Init] - > [Psychicing startPsychic] - > [MainClass add to array] - > [MainClass add to self]
I hope i have explained it clearly enough, if you need more clarification let me know.
So basically:
[MainClass Init] -> [Psychicing startPsychic] -> [MainClass add to array] -> [MainClass add to self]
推荐答案
我假设_Objects(它应该是一个小写的o遵守约定)存储对象除了Psychicing对象并且你试图在 - (void)Touches ...方法(也应该是小写)中拉出Psychicing对象。如果是,您可以:
I'm assuming the _Objects (which should be a lowercase o to follow conventions) is storing objects other than the Psychicing object and you're trying to pull just the Psychicing object out of it in the -(void)Touches... method (which also should be lowercase). If so, you could do:
for (id obj in _Objects)
{
if ([obj isMemberOfClass:[Psychicing class]])
[self addChild:obj.psychicParticle];
}
这将只导致数组中的Psychicing对象被添加为子自我。
That will cause only the Psychicing objects in the array to be added as a child to self.
看起来你有另一个错误,但如果你粘贴的代码是你的真正的代码。 init应定义为:
It looks like you do have another error though if the code you pasted in is your real code. Init should be defined as:
- (void) init{
_Objects = [[NSMutableArray alloc]init];
Psychicing *psy = [[Psychicing alloc]init];
[psy startPsychic];
[_Objects addObject: psy];
[psy release];
}
<正如你写的,它是一个方法变量在init方法和泄漏。所以当你尝试访问_tools中的_Objects时,_Objects很有可能是nil。
with _Objects defined as an instance variable (or property) in the class's interface. As you wrote it, it's a method variable in the init method and is leaking. So when you try to access _Objects in -touches, _Objects is most likely nil.
这篇关于从NSArray检索类对象并添加到self的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!