JordanSun
JordanSun

Reputation: 11

class instance cannot be reference inside IBAction method in objective-c

I am writing a small card game for iphone,

say, i have a player.h/.m class, which have a Mutable Array myCard

I write

@interface Player : NSObject{
    NSMutableArray *myCard;
}
@property (nonatomic) NSMutableArray *myCard;

@end

in a view controller, controller.h

#import "Player.h"
@interface controller : UIViewController {
    Player *playerMe;
}

in a view controller, controller.m

 - (Player *)playerMe
{
    if (!playerMe) playerMe = [[Player alloc] init];
    return playerMe; 
}

then i have some instance method to addObject in playerMe.myCard, everything is fine till now.

I have a button which was added in IB, and have a IB action:

- (IBAction)btnSort:(id)sender {
    //do something with self.playerMe.myCard
}

Problem then appears, I look at the debug window and look up the value in all variables. Before the button was clicked, the self.playMe.myCard is fine with a certain object there. once the button was clicked, the self.playerMe.myCard is nil and have nothing inside

So, i would like to know why the self.playerMe.myCard cannot be reference while self.playMe is alright, is that about the @property definition?

Thanks!

Upvotes: 0

Views: 301

Answers (2)

JordanSun
JordanSun

Reputation: 11

i finally solved the problem by changeing the @property attribut and a custom setter for myCard

player.h

@property (nonatomic,retain) NSMutableArray *myCard;

player.m

- (void)setMyCard:(NSMutableArray *)aCardArr
{
    [myCard autorelease];
    myCard = [[NSMutableArray arrayWithArray:aCardArr] retain];
}

Maybe this is just basic stuff, but as a newer to objective-c, just post back here for someone like me as a reference.

Thanks for all of your help

Upvotes: 1

beryllium
beryllium

Reputation: 29767

Try to make explicit retain property for myCard. It may be a leak when using assign property by default.

@property (nonatomic, retain) NSMutableArray *myCard;

Upvotes: 1

Related Questions