Get instance variable?
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.
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.
精彩评论