tags:

views:

55

answers:

2

Hello, I have the following class:

@interface Gamer : CCNode {
NSMutableArray * cards;
}
@property (nonatomic, retain) NSMutableArray * cards;

+(id) CreatePlayer;
-(BOOL)SetCardsArr:(NSMutableArray *) cs;
-(BOOL)GetCardForMove:(Card*) card actionCard:(Card*)selCard;
@end

@implementation Gamer

@synthesize cards;

+(id) CreatePlayer
{
return [[self alloc] init];
}

-(BOOL) SetCardsArr:(NSMutableArray *) cs
{
if (!cs) return NO; 
cards = [cs copy];
return YES;  
}
-(BOOL)GetCardForMove:(Card*) card actionCard:(Card*)selCard;
{
for (Card * curCard in cards)
    {
    if ([curCard GetCardSuit] == [selCard GetCardSuit])
            {
        selCard = curCard;
        break;
    }
}
return YES;
}

 -(id) init
 {
if(![super init]) return nil;

return self;
 }
 - (void)dealloc
 {
[cards release];
[super dealloc];
 }
@end

On the my main game class I set gamer array with help of the SetCardsArr method. And after some actions I am trying to get Gamer card by GetCardForMove method like this:

Card * moveCard = nil;
    Card * selCard = card;
[mGamer GetCardForMove:moveCard actionCard:selCard];

The GetCardForMove function works fine, card found and assigned properly but Card * moveCard is nil :(. I am new to Objective-C and a little confused, please point me on my errors.

A: 

Actually the card isn't assigned at all. If you want your code outside the method to see the card, do either this (the better approach):

- (Card *)cardForActionCard: (Card *)selCard {
  //stuff
  return usefulCard;
}

or this (most similar to your current code):

- (BOOL)getCardForMove: (Card **)card actionCard: (Card *)selCard {
  //stuff
  if (card) {
    *card = usefulCard;
  }
  return YES;
}

By the way, this is unrelated to your question but your code contains a couple of problems regarding memory management (I assume as you have a dealloc method that you're in a retain-counted environment). No need to cover them here, just run "Build and Analyze" and fix the problems it reports.

Graham Lee
No -- recommending pass by reference (out parameter) is completely the wrong thing to do. Don't do it that way! The "similar code" is just wrong! Use the first method that Graham suggests.
bbum
A: 

Thanks for help. It helps me. And I have an another little question. I need to fill the array

 NSMutableArray * cards;

with Card objects one by one. Is it correct method for adding Card to cards array?

-(BOOL) AddCardToArr:(Card *) card
{
if (!card) return NO;   
[cards addObject:card];
return YES;
}

This is how I use the AddCardToArr in another class(mGamer is the Gamer class object):

for (int i=0;i<5; ++i)
{
  Card * card = (Card *)[cards objectAtIndex:i];      
  [mGamer AddCardToArr:card];
}

Any advice will be very helpful.

Romula