Retrieving Class Object from NSArray and adding to self

家住魔仙堡 提交于 2019-12-13 05:40:45

问题


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];
}

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...
}

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];
     }
}

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]


回答1:


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];
}

That will cause only the Psychicing objects in the array to be added as a child to self.

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];
}

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.




回答2:


Okay, with the help of McCygnus I got it working, the only thing missing with a pointer to the id object:

 for (id obj in _Objects){
        if ([obj isMemberOfClass:[Psychicing class]]){
            Psychicing *apsy = obj;
            [apsy.psychicParticle setPosition:location];
            [self addChild:apsy.psychicParticle];
        }

    }


来源:https://stackoverflow.com/questions/5752443/retrieving-class-object-from-nsarray-and-adding-to-self

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!