I create an array of custom objects called players.
@interface Player : NSObject
{
NSString *name;
NSNumber *spd;
NSNumber *atk;
NSNumber *def;
}
@property(nonatomic, retain) NSString *name;
@property(nonatomic, retain) NSNumber *spd;
@property(nonatomic, retain) NSNumber *atk;
@property(nonatomic, retain) NSNumber *def;
@end
#import "Player.h"
@implementation Player
@synthesize name;
@synthesize spd;
@synthesize atk;
@synthesize def;
@end
That seems ok.
So I have a function that setups an array full of Player objects.
-(void) initTheGame
{
NSLog(@" initTheGame");
playerArray =[[NSMutableArray alloc] init];
p1Cards =[[NSMutableArray alloc] init];
p2Cards =[[NSMutableArray alloc] init];
for (int i = 0; i < 20; i++)
{
Player *myPlayer = [[Player alloc] init];
myPlayer.name =[NSString stringWithFormat:@"Name%d", (rand()%99)];
myPlayer.spd = [NSNumber numberWithInteger:(rand() % 100)];
myPlayer.atk = [NSNumber numberWithInteger:(rand() % 100)];
myPlayer.def = [NSNumber numberWithInteger:(rand() % 100)];
[playerArray addObject:myPlayer];
[myPlayer autorelease];
}
[self dealHands];
[self setupValuesForUI];
}
It works as expected. Fills up the array full of Player objects containing random data.
-(void) setupValuesForUI
{
NSLog(@"setupValuesForUI");
Player *p1 = [[Player alloc] init];
p1 = [playerArray objectAtIndex:0];
p1Name.text = p1.name;
[p1Speed setTitle:[NSString stringWithFormat:@"Spd: %@",[p1.spd stringValue] ] forState:UIControlStateNormal];
[p1Attack setTitle:[NSString stringWithFormat:@"Atk: %@",[p1.atk stringValue] ] forState:UIControlStateNormal];
[p1Defense setTitle:[NSString stringWithFormat:@"Def: %@",[p1.def stringValue] ] forState:UIControlStateNormal];
[p1 autorelease];
}
This function uses some IBOutlets to set the Text values for a Lable and 3 Buttons. All work ok they display there data.
Now when i press a button and an IBAction method gets called my app crashes out with an EXEC_BAD_ACCESS
The code hasnt changed, I try and access the object in the same way, but it seems to have disappeared. :(
Can somebody explain what I did wrong. I'm a newbie to Objective C so forgive me if this is
an obvious problem to you. I can find it after hours of trying to debug it.
-(IBAction) spd
{
Player *p1 = [[Player alloc] init];
p1 = [playerArray objectAtIndex:0];
int x = [p1.spd integerValue]; // this line crashes out the app
}