To start let me tell you I am a total Objective-C beginner. This is my problem:
I have a NSMutableArray that stores objects, (Player) that has the name of the player and his/her score.
I am able to add objects to the array using addObject, but I am having trouble traversing this array. This
is how I do it:
// Get the reference to the array
NSMutableArray *myarray = [delegate getArray];
// Create a numerator
NSEnumerator *e = [myarray objectEnumerator];
id object;
while (object = [e nextObject])
{
[object printPlayer];
}
The method printPlayer belongs to the Player class and it just prints the name and the score.
The problem is when I have three players in the array and I am trying to print the content, it reaches this error inside the printPlayer method:
Thread 1: EXC_BAD_ACCESS(code=1, address=0x0000008)
Strangely if I use NSLog(@"%@", object); instead of [object printPlayer]; it prints a reference to the object and does not reach any error.
Anyone could point me what could be the problem when I try to use [object printPlayer]
Cheers
Update 1:
This is my printPlayer method:
-(void) printPlayer
{
NSLog(@"\n\nName: %@\nScore: %d", playerName, playerScore);
}
Update 2:
Player.h:
@interface PROGPlayer : NSObject
@property (nonatomic, assign) NSString *playerName;
@property (nonatomic, assign) int playerScore;
-(id) init: (NSString *) n;
-(void) printPlayer;
@end
Player.m:
#import "PROGPlayer.h"
@implementation PROGPlayer
@synthesize playerName;
@synthesize playerScore;
/**
* Player's class constructor
* @param n Player's name
* @param s Player's score
*/
-init: (NSString *) n
{
if (!(self = [super init])) return nil;
else
{
playerName = n;
playerScore = 0;
}
return self;
}
-(void) printPlayer
{
NSLog(@"\n\nName: %@\nScore: %d", playerName, playerScore);
}
@end
Your playerName property should best be copied instead of assigned
When trying to access the assigned value, the object most likely is gone causing the bad access.
Also remember to release playerName in dealloc when you set the property to copy.
Cheers